在学习了组合数据类型和文件操作之后就可以做出下面的文本词频统计的小程序了:
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)
#输出结果,前十位最高频词汇
for i in range(10):
#从items[i]中一次返回单词和单词的词频
word, count = items[i]
print("#{0:<10}{1:>5}".format(word,count))
#输出:
#the 39
#to 38
#conflict 27
#and 27
#of 20
#it 19
#a 15
#is 15
#we 14
#in 13
可见作者的英文水平仅限于助词、介词和连词了【雾】
2. 下面是中文文本的词频统计,统计了作者的一篇中文论文
import jieba
#定义文件读取函数
def gettext():
text = open("目标文件.txt","r").read()
text = text.lower()
for ch in '~!@#¥%……&*()——+=-·{}【】、‘;:“|?><,./1234567890abcdefghijklmnopqrstuvwxyz':
text.replace(ch, " ")
return text
#使用jieba分词处理得到词库
words = jieba.lcut(gettext())
counts = {}
for word in words:
#不统计单字词汇
if len(word)==1:
continue
else:
counts[word] = counts.get(word,0)+1
#转换为列表类型
items = list(counts.items())
items.sort(key=lambda x:x[1], reverse=True)
for i in range(10):
word, count = items[i]
a = 20 - len(word)*2
b = str(count)
a = a - len(b)
ch = " "*a
print("#{0}{1}{2}".format(word, ch, count))
#输出:
#自己 128
#职业 120
#工作 79
#企业 78
#人力 76
#资源管理 74
#个人 62
#就业 60
#管理 54
#能够 54
最后需要注意的是,文本文件要放在项目的源文件夹中才能读取到