我是靠谱客的博主 英俊唇彩,这篇文章主要介绍Python 读取文本中的单词,现在分享给大家,希望可以做个参考。

# -*- coding:utf-8 -*-  
import io  
import re  
  
class Counter:  
def __init__(self, path):  
""" 
:param path: 文件路径 
"""  
self.mapping = dict()  
with io.open(path, encoding="utf-8") as f:  
data = f.read()  
words = [s.lower() for s in re.findall("w+", data)]  
for word in words:  
self.mapping[word] = self.mapping.get(word, 0) + 1  
  
def most_common(self, n):  
assert n > 0, "n should be large than 0"  
return sorted(self.mapping.items(), key=lambda item: item[1], reverse=True)[:n]  
  
if __name__ == '__main__':  
most_common_5 = Counter("importthis.txt").most_common(5)  
for item in most_common_5:  
print(item)  

 

最后

以上就是英俊唇彩最近收集整理的关于Python 读取文本中的单词的全部内容,更多相关Python内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(120)

评论列表共有 0 条评论

立即
投稿
返回
顶部