在学习了组合数据类型和文件操作之后就可以做出下面的文本词频统计的小程序了:
1. 下面是英文文本的词频统计,统计了作者的一篇英文论文
#文本词频统计:英文文本
def gettext():
#从文件中获取文本
text = open("target.txt","r").read()
#将文本中的所有大写字母转换为小写字母
text = text.lower()
#替换文本中的所有特殊符号为空格
for c in '!"#$%^&*()_+-=@[]{}|\?/<>,.:;~·`、“”‘’':
text = text.replace(c," ")
#返回文本
return text
#获取处理好的文本
txt = gettext()
#将处理好的文本切分成列表
words = txt.split()
#定义空字典
count = {}
#遍历列表,统计词出现的次数
for word in words:
count[word] = count.get(word,0)+1
#将统计好的字典转换成列表类型,以便进行排序
items = list(count.items())
#将列表按照count中键值的从大到小的顺序进行排序
items.sort(key = lambda x:x[1], reverse = True)
#输出结果,前十位最高频词汇