综合练习:词频统计

下载一首英文的歌词或文章

将所有,.?!’:等分隔符全部替换为空格

将所有大写转换为小写

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])
原文地址:https://www.cnblogs.com/wlh0329/p/8659505.html