如何用python对文章中文分词并统计词频

Python010

如何用python对文章中文分词并统计词频,第1张

1、全局变量在函数中使用时需要加入global声明

2、获取网页内容存入文件时的编码为ascii进行正则匹配时需要decode为GB2312,当匹配到的中文写入文件时需要encode成GB2312写入文件。

3、中文字符匹配过滤正则表达式为ur'[\u4e00-\u9fa5]+',使用findall找到所有的中文字符存入分组

4、KEY,Value值可以使用dict存储,排序后可以使用list存储

5、字符串处理使用split分割,然后使用index截取字符串,判断哪些是名词和动词

6、命令行使用需要导入os,os.system(cmd)

首先要说明一个概念:gbk编码里一个中文字符的‘长度’是2。

str = '中国'  #gbk编码

要取得'中'这个字符,需要用分片str[0:2],而不是索引str[0]。

以z4为例,下面这些代码的效果是这样的。

x = '同舟共济与时俱进艰苦奋斗'

i+= z4.findall(x) # 返回['同舟共济','与时俱进', '艰苦奋斗']

i+= z4.findall(x[2:]) # 返回['舟共济与', '时俱进艰']

i+= z4.findall(x[4:]) # 返回['共济与时', '俱进艰苦']

i+= z4.findall(x[6:]) # 返回['济与时俱', '进艰苦奋']

目的是取得所有连续4字中文字符串。

def statistics(astr):

# astr.replace("\n", "")

slist = list(astr.split("\t"))

alist = []

[alist.append(i) for i in slist if i not in alist]

alist[-1] = alist[-1].replace("\n", "")

return alist

if __name__ == "__main__":

code_doc = {}

with open("test_data.txt", "r", encoding='utf-8') as fs:

for ln in fs.readlines():

l = statistics(ln)

for t in l:

if t not in code_doc:

code_doc.setdefault(t, 1)

else:

code_doc[t] += 1

for keys in code_doc.keys():

print(keys + ' ' + str(code_doc[keys]))