首页 > 其他 > 详细

819. 最常见的单词

时间:2020-04-14 14:42:16      阅读:61      评论:0      收藏:0      [点我收藏+]

技术分享图片

 

 

 技术分享图片

技术分享图片

 

 

 

思路:
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"]))

 

 

819. 最常见的单词

原文:https://www.cnblogs.com/panweiwei/p/12697860.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!