思路:
1、将整个段落中的字母转成小写;
2、用各标点符号分割段落;
3、遍历2返回的list,统计不在禁用表中且出现次数最多的单词并返回。
1 import re 2 3 class Solution(object): 4 def mostCommonWord(self, paragraph, banned): 5 """ 6 :type paragraph: str 7 :type banned: List[str] 8 :rtype: str 9 """ 10 # 段落中的字母全部转成小写 11 paragraph = paragraph.lower() 12 # 用多种标点符号和空格分割段落 13 listpara = re.split(r‘[!?\‘.;,\s]\s*‘, paragraph) 14 # print(listpara) 15 # 计数器 16 num = 0 17 # 返回值,即出现次数最多,同时不在禁用列表中的单词 18 ans = "" 19 for i, ch in enumerate(listpara): 20 if ch not in banned and listpara.count(ch) > num: 21 num = listpara.count(ch) 22 ans = ch 23 return ans 24 25 26 if __name__ == ‘__main__‘: 27 solution = Solution() 28 print(solution.mostCommonWord("Bob hit a ball, the hit BALL flew far after it was hit.", ["hit"])) 29 print(solution.mostCommonWord("a, a, a, a, b,b,b,c, c", ["a"]))
原文:https://www.cnblogs.com/panweiwei/p/12697860.html