2018年9月7日在百度google没有找到python统计中文词组的,查出来的都是统计英文单词,词组的,所以我想来实现python中文词组统计分享。
首先我是用textrank4zh库将句子转化成词组
from textrank4zh import TextRank4Keyword
text = open("wc_clear.txt").read()
tr4w = TextRank4Keyword()
tr4w.analyze(text=text, lower=True, window=2)
with open("wc_clear_phrase.csv",'w') as f:
for words in tr4w.words_all_filters:
f.write('/'.join(words))
其中wc_clear.txt
而wc_clear_phrase.csv就变成:
之后运行下列代码:
#_*_coding:utf-8_*_
import pandas as pd
text = open("wc_clear_phrase.csv").read()
li=text.split("/")
counte_phrase_phrase=[]
counte_phrase_times=[]
for i in range(5):
counte_phrase_times.append(text.count(li[i]))
counte_phrase_phrase.append(li[i])
pdf=pd.DataFrame({"phrase":counte_phrase_phrase,
"times":counte_phrase_times}).sort_values("times",ascending=False)
print(pdf)
输出:
因为我文本多,如果全部运行起来很慢,所以我演示用了range(5),但在实际运行时我是用range(len(li))。
嗯,代码很简单,用"context.count(str)"如:text.count(li[i]) 返回int型匹配到的次数。
再用pandas.DataFrame存二维数组。
假如有需要的话进一步分析统计:
from matplotlib.font_manager import FontProperties
import seaborn as sns
zhfont=FontProperties(fname=r'C:\Windows\Fonts\simhei.ttf',size=14)
sns.set(font=zhfont.get_name())
sns.barplot("phrase", "times", palette="RdBu_r", data=pdf_)
值得注意的是zhfont=FontProperties(fname=r'C:\Windows\Fonts\simhei.ttf',size=14) 参考知乎的改seaborn 的字体,要不然seaborn图是显示不了中文。
输出为:
嗯,很简单是不是!