一、前言
前几天在Python最强王者交流群【Wendy Zheng】问了一个英文文本中统计关键词的问题,这里拿出来给大家分享下。
二、实现过程
针对这个问题,本文给出一个思路方法,也许有帮助,首先我们需要将Excel中的文本进行导入到一个文本文件中去,代码如下:
# coding: utf-8
import pandas as pd
df = pd.read_excel(‘./文本.xlsx’)
# print(df.head())
# df[‘专业关键词’]
for text in df[‘工作要求’]:
# print(text)
if text is not None:
with open(‘工作要求.txt’, mode=’a’, encoding=’utf-8′) as file:
file.write(str(text))
print(‘写入完成’)
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
接下来就可以针对这个文本文件进行相关的词频统计了,如果你有自己自定义的关键词,也可以就着关键词去统计,没有的话,就自己在关键词范围内,任意取多少个关键词都可以,相关的代码如下所示:
from collections import Counter
import pandas as pd
df = pd.read_excel(‘./文本.xlsx’)
# print(df.head())
words = []
with open(‘工作要求.txt’, ‘r’, encoding=’utf-8′) as f:
line = f.readlines()
for word in line[0].split(‘ ‘):
words.append(word)
print(len(words))
counter = Counter(words)
# print(counter)
# df[‘专业关键词’]
for text in df[‘专业关键词’]:
for k, v in counter.items():
if k == text:
print(k, v)
这个代码对于英文文本还是适用的,不过有个小问题,如下。
最后这里也给出中文分词的代码和可视化代码,两者结合在一起的,感兴趣的小伙伴们可以试试看。
登录后复制
from collections import Counter # 统计词频
from pyecharts.charts import Bar
from pyecharts import options as opts
from snownlp import SnowNLP
import jieba # 分词
with open(‘text_分词后_outputs.txt’, ‘r’,encoding=’utf-8′) as f:
read = f.read()
with open(‘stop_word.txt’, ‘r’, encoding=’utf-8′) as f:
stop_word = f.read()
word = jieba.cut(read)
words = []
for i in list(word):
if i not in stop_word:
words.append(i)
columns = []
data = []
for k, v in dict(Counter(words).most_common(10)).items():
columns.append(k)
data.append(v)
bar = (
Bar()
.add_xaxis(columns)
.add_yaxis(“词频”, data)
.set_global_opts(title_opts=opts.TitleOpts(title=”词频top10″))
)
bar.render(“词频.html”)