统计一个文本中单词频次最高的10个单词?
- import re
-
- # 方法一
- def test(filepath):
-
- distone = {}
-
- with open(filepath) as f:
- for line in f:
- line = re.sub("\W+", " ", line)
- lineone = line.split()
- for keyone in lineone:
- if not distone.get(keyone):
- distone[keyone] = 1
- else:
- distone[keyone] += 1
- num_ten = sorted(distone.items(), key=lambda x:x[1], reverse=True)[:10]
- num_ten =[x[0] for x in num_ten]
- return num_ten
-
-
- # 方法二
- # 使用 built-in 的 Counter 里面的 most_common
- import re
- from collections import Counter
-
-
- def test2(filepath):
- with open(filepath) as f:
- return list(map(lambda c: c[0], Counter(re.sub("\W+", " ", f.read()).split()).most_common(10)))
解压密码: detechn或detechn.com
免责声明
本站所有资源出自互联网收集整理,本站不参与制作,如果侵犯了您的合法权益,请联系本站我们会及时删除。
本站发布资源来源于互联网,可能存在水印或者引流等信息,请用户自行鉴别,做一个有主见和判断力的用户。
本站资源仅供研究、学习交流之用,若使用商业用途,请购买正版授权,否则产生的一切后果将由下载用户自行承担。