python1.返回一个字符串中出现次数第二多的单词 2.字符串中可能有英文单词、标点、空格 3.字符串中的英文字符全部是小写

import re
from collections import Counter
def second_count_word(s):
    # # 利用正则按标点和空格切割,有其他标点可以添加到[]内
    # lt = re.split('[ ,.:]',s)
    # # 利用Counter直接统计列表中单词出现的次数
    # c = Counter(lt)
    # # c.most_common(2)返回一个出现次数最多和第二多的列表,
    # # 列表里面是单词和次数的元组,直接取出返回即可
    # return c.most_common(2)[1][0]
    # # 以上三行可以简写为一行直接返回(功能同上)
    return Counter(re.split('[ ,.:]',s)).most_common(2)[1][0]
s = 'hello,welcome to you zhengzhou.you:are,hi.to,to'
print(second_count_word(s))
行成于思毁于随
原文地址:https://www.cnblogs.com/chengbo2130/p/10083627.html