Python 如何对输出的词频结果按字母顺序排序(NLTK)

Python013

Python 如何对输出的词频结果按字母顺序排序(NLTK),第1张

import nltk

file_b = open('a.txt', 'r')

tokens = nltk.word_tokenize(file_b)

fdist1 = nltk.FreqDist(tokens)

for key,val in sorted(fdist1.iteritems())[:5]:

    print ("{1}: {0}".format(key, round(val / len(tokens), 2)))

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)