python pynlpir分词及词频统计

社会主义新天地 提交于 2020-02-18 14:42:38

"""
功能:PyNLPIR文本预处理
过程:文本分词,词频统计
时间:2020年02月16日
作者:Angel

import pynlpir
pynlpir.open()
#文本分词、词频统计
p = open(r'C:\Users\Angel\Desktop\python分词\test.txt', 'r', encoding = 'utf-8')
q = open(r'C:\Users\Angel\Desktop\python分词\test_result.txt', 'w', encoding = 'utf-8')

counts = {}      #定义空字典
#直接打印出结果
for line in p.readlines():
    words = pynlpir.segment(line, pos_english=False)     # 把词性标注语言变更为汉语
    for word,flag in words:
        q.write(str(word) + str(flag) + " ")
        if len(word) == 1:
            continue
        else:
            rword = word
            s = rword+','+flag                #将分词和词性进行拼接
        counts[s] = counts.get(s,0) + 1       #同时统计分词和词性的词频,存储在字典counts中
    q.write('\n')

#遍历字典输出
for count in counts:
    print(count+':'+str(counts[count]))                 

#将字典转换为列表排序后遍历输出
items = list(counts.items())                                
items.sort(key=lambda x:x[1],reverse = True)            
for item in items:
    print(item)

p.close()

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!