【编译原理】Python实现对一个英文文本的词频统计

利用Python实现对一个英文文本的词频统计。文本链接:https://www.philippinetimes.com/news/257886068/australia-blocks-chinese-firms-huawei-zte-from-5g-network 

1、元组创建

tup1 = ('Google', 'atguigu', 1997, 2000);
tup2 = (1, 2, 3, 4, 5 );
tup3 = "a", "b", "c", "d"; # 不需要括号也可以

2、字典创建

dict = {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'}
dict = {x:x+1 for x in range(10)}

3、Set集合创建

s = {'name','aa','bb'}
s = set(序列) # dict序列,值添加key
s = {x for x in range(10) if x not in range(5,10)}

按照图4.2所示的流程图进行文件词频的统计,具体的代码详见附录。

图4.2  词频统计流程图

3 词频统计结果

(1)具体词频统计见附件ex1_词频统计结果.xlsx和ex1_词频统计结果.txt。第一个文件为自己编写的代码,在存储结果的时候对数据进行了一些处理,里面的数据较为规范;第二个文件参考老师讲解,之后在存储文件时采用了列表格式存储。
           

图4.3  词频统计结果示意图

由上述文件可以看出,词频前五的有the、to、and、huawei、that,多数为指示代词或连词。

(2)根据词频生成词云图,见图4.4。

图4.4 词云图

参考资料

  1. Anaconda安装及使用教程:https://zhuanlan.zhihu.com/p/32805175
  2. Python 基础入门--简介和环境配置:https://www.jianshu.com/p/8e56607b0abc
import re
file=open('ex1_news.txt',encoding='ansi')
lowerText=file.read().lower()
file.close()
arr=re.split('[ ,.+"\n]',lowerText)
voc={};
for each in arr:
    if each not in voc:
        voc[each]=1;
    else:
        voc[each]+=1;
voc.pop('');
vocSorted=sorted(voc.items(),key=lambda x:x[1],reverse=True)# 按照键值进行排序
newFile=open('ex1_词频统计结果.txt','w')
newFile.write(str(vocSorted))
newFile.close()

#根据词频生成云图
from wordcloud import WordCloud, ImageColorGenerator
from PIL import Image
import numpy as np
image=Image.open('china_map.jpg');
graph = np.array(image)
# 参数分别是指定字体、背景颜色、最大的词的大小、使用给定图作为背景形状
wc = WordCloud(font_path="C:/Windows/Fonts/simfang.ttf", background_color='white', max_words=100, mask=graph)
wc.generate_from_frequencies(voc)#根据给定词频生成词云
image_color = ImageColorGenerator(graph)
#生成图片
image=wc.to_image()
#显示图片
image.show()
#存储图片
image.save('云图1.jpg')

猜你喜欢

转载自blog.csdn.net/weixin_43442778/article/details/114970932