Fork me on GitHub

py统计单词个数

任一个英文的纯文本文件,统计其中的单词出现的个数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import string
f= open(r'C:\Users\12905\Desktop\1.txt', 'r+') #从文件中读取内容
str1= f.read()
str= str1.lower() #全部切换成小写
list= str.split() #切片
list1= []
for i in range(0, len(list)):
list[i]= list[i].strip(string.punctuation)
for word in list:
if word not in list1:
list1.append(word)
for word in list1:
print(word, list.count(word))

运行结果如下图所示:
1

Your support will encourage me to continue to create!