Python安装及词频分析手记
背景
疫情期间拿到一份关于中小企业的经营状况的调查数据,想通过程序对其中的企业诉求进行词频分析。
由于在家里办公,电脑中没有开发环境,只能从头开始。
工具
系统环境:Windows10家庭中文版
编程语言:Python
开发环境:Visual Studio Code
安装
安装python
下载地址:https://www.python.org/downloads/,选择最新的Python 3.8.1版本。

下载后直接点击安装,注意要勾选添加环境变量,即第一步最下面的“Add Python 3.8 to PATH”,同时建议把安装路径修改简单一点。
安装时忘了截图,用网上的图代替吧。

安装后打开windows的“命令提示符”,直接输入python回车,就可以进入Python命令环境。输入exit()回车即可退出。

安装Visual Studio Code
下载地址:https://code.visualstudio.com/,选择Windows x64版本

下载后点击安装,一路“下一步”即可。
配置
配置Visual Studio Code
打开Visual Studio Code,在左侧扩展应用商店中添加python插件和中文语言包。

选择一个文件夹作为项目代码文件夹。

添加第三方工具包
主要是flake8和yapf。一个是Python静态代码检查工具,一个是Python格式化工具。
python自带安装了Python包管理工具pip。
直接打开命令提示符,输入pip list可查看已经安装的工具包。

如果没有,可以输入pip install安装。比如输入pip install flake8下载安装flake8,输入pip install yapf 下载安装yapf。

打开Visual Studio Code,点击左下角齿轮按钮,打开“设置”选项,在工作区域输入以下内容保存:
{
"python.linting.flake8Enabled": true,
"python.formatting.provider": "yapf",
"python.linting.flake8Args": ["--max-line-length=248"],
"python.linting.pylintEnabled": false
}

编写程序文件
了解界面
Visual Studio Code继承了微软家族界面方便、插件丰富、容易上手的特点,而且开源、跨平台、运行快。
左侧是功能导航。右边是工作区域,可以切换不同视图。下边是运行调试终端。

配置python编译设置
为方便调试,打开Visual Studio Code“运行和调试”功能,添加配置,在右边配置文件中增加一行:
"stopOnEntry": false,

新建程序文件
在Visual Studio Code新建文件,保存为后缀名为.py的phthon程序源文件。
按快捷键F5即可运行调试。
修改词频分析程序文件
网上关于词频分析的代码很多,随便找了一个,下载保存为.py文件打开,直接改改。
程序代码:
import jieba
txt = open("词频分析文本.txt", encoding="utf-8").read()
#加载停用词表
stopwords = [
line.strip()
for line in open("StopWords.txt", encoding="utf-8").readlines()
]
words = jieba.lcut(txt)
counts = {}
for word in words:
#不在停用词表中
if word not in stopwords:
#不统计字数为一的词
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(30): #统计前30个
word, count = items[i]
print("{:<10}{:>7}".format(word, count))
python语言就是简单方便,借助工具库,简单几行代码就完成了。
在Visual Studio Code中按下快捷键Alt+Shift+F即可借助yapf自动格式化代码。
代码中import jieba,需要调用jieba分词工具。可采用前述的pip方法,在命令提示符中输入pip install jieba安装。
统计出来,最高频的10个词分别是:
企业 812,希望 744,政府 608,减免 490,疫情 438,口罩 414,房租 320,复工 320,员工 312,补贴 299。
生成词云
更炫的就是做一张词云图,关于词云的代码也很多,需要的第三方工具包也多。
pip install re # 正则表达式库
pip installcollections # 词频统计库
pip installnumpy # numpy数据处理库
pip installjieba # 结巴分词
pip installwordcloud # 词云展示库
pip installpillow # 图像处理库
pip installmatplotlib.pyplot # 图像展示库
在安装词云展示库wordcloud时出了点问题。
一开始报错,需要安装Visual C++ 14.0,下载安装后还是不行,通过pip安装行不通了。
后来按网上指点,下载第三方包安装。
安装词云展示库wordcloud
下载地址:https://www.lfd.uci.edu/~gohlke/pythonlibs/#wordcloud,选择最新适配版本wordcloud‑1.6.0‑cp38‑cp38‑win_amd64.whl下载。
将文件复制到pip安装的位置,即Python安装文件夹的Scripts目录下。
要安装.whl文件,先通过命令提示符,输入"pip install wheel"安装 wheel功能。
在命令提示符中,进入刚才.whl复制粘贴到的文件夹,比如cd C:\Python\Python38\Scripts。
输入安装指令,格式为pip install wordcloud‑1.6.0‑cp38‑cp38‑win_amd64.whl ,回车安装。

生成词云图片
wordcloud功能丰富,主要做三件事:文本预处理、词频统计、将高频词以图片形式进行彩色渲染

选择重庆地图作为背景,屏蔽掉一些意义不大的词,来看看这次生成的词云图片:
