利用jieba库对李之仪的《卜算子》进行分词
按照单词出现的次数从高到低排序。因为字典类型是无序的,无法排序,因此将counts转为列表类型(列表排序的知识点详见“python中列表的sort方法使用详解”)。查看排序后的结果。
import jieba
txt ='''
卜算子
【宋】李之仪
我住长江头,君住长江尾。
日日思君不见君,共饮长江水。
此水几时休,此恨何时已。
只愿君心似我心,定不负相思意。
'''
words = jieba.lcut(txt)
counts = {}
for word in words:
counts[word] = counts.get(word,0) + 1
items = list(counts.items())
items.sort(key=lambda x:x[1], reverse=True)
for item in items:
print(item)
为了增强排序后结果的可读性,利用format调整输出的格式。
import jieba
txt ='''
卜算子
【宋】李之仪
我住长江头,君住长江尾。
日日思君不见君,共饮长江水。
此水几时休,此恨何时已。
只愿君心似我心,定不负相思意。
'''
words = jieba.lcut(txt)
counts = {}
for word in words:
counts[word] = counts.get(word,0) + 1
items = list(counts.items())
items.sort(key=lambda x:x[1], reverse=True)
for item in items:
word,count=item
print("{0:<10}{1:>5}".format(word,count))