1. 程式人生 > >python1.返回一個字串中出現次數第二多的單詞 2.字串中可能有英文單詞、標點、空格 3.字串中的英文字元全部是小寫

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))