1.英文词频统
下载一首英文的歌词或文章
将所有,.?!’:等分隔符全部替换为空格
将所有大写转换为小写
sep = ''',.'?!;:'"''';
for i in sep:
worldSet = news.replace(i,' ');
worldSet= news.lower().split();
生成单词列表
print(worldSet)
生成词频统计
worldDict = {}
for w in worldList:
worldDict[w] = worldSet.count(w)
排序
worldList = list(worldDict.items()) worldList.sort(key=lambda x: x[1], reverse=True)
排除语法型词汇,代词、冠词、连词
exception = {'in', 'to', 'your', 'you', 'and', 'the', 'for','a','i'};
worldList = set(worldSet) - exception;
输出词频最大TOP20
for i in range(20):
print(worldList[i])
2.中文词频统计
import jieba
f=open('s.txt','r',encoding="UTF-8")
str1=f.read()
f.close()
str2=list(jieba.cut(str1))
delset = {",","。",":","“","”","?"," ",";","!","、","ufeff","
"}
stringset = set(str2) - delset
countdict = {}
for i in stringset:
countdict[i] = str2.count(i)
dictList = list(countdict.items())
dictList.sort(key = lambda x:x[1],reverse = True)
f = open("E:/结果.txt", "a")
for i in range(20):
f.write('
' + dictList[i][0] + " " + str(dictList[i][1]))
f.close()
