Python统计.txt文本中每个英文单词个数
程序员文章站
2022-03-10 22:17:02
...
目录
需求:
给定一个word.txt文件,统计文件中每个英文单词出现的次数,保存在word2.txt中。
实现:
word.txt:
Python2.7下的统计脚本:
import collections
import re
def word_cal():
with open('word.txt','r') as fp:
content = re.split('[,. ]', fp.read())
b = collections.Counter(content)
with open('word2.txt','w') as result_file:
for key,value in b.items():
result_file.write(key+':'+str(value)+'\n')
def main():
word_cal()
if __name__ == '__main__':
main()
统计结果保存到word2.txt中:
上一篇: 【ML】Python准备篇(2)Sublime环境
下一篇: Python环境搭建