一个小问题却能极大挫伤学习热情,愣是两天不想碰。
在学习中国大学mooc上嵩天老师的《python语言程序设计》,第六周的实例文本词频统计(中遇到问题,按照老师的代码在mac上操作不可行,后来改动一下,终于成功。
这个实例是要统计三国演义出现频次最高的人名,(你猜是曹操还是孔明?答案在文末,猜对没奖但有成就感哈哈)
完整代码
#CalThreeKingdomsV1.py
import jieba
txt = open("threekingdoms.txt", "r", encoding='utf-8').read()
words = jieba.lcut(txt)
counts = {}
for word in words:
if len(word) == 1:
continue
else:
counts[word] = counts.get(word,0) + 1
items = list(counts.items())
items.sort(key=lambda x:x[1], reverse=True)
for i in range(15):
word, count = items[i]
print ("{0:<10}{1:>5}".format(word, count))
问题出在第二行
老师代码
txt = open("threekingdoms.txt", "r", encoding='utf-8).read()
实际可行代码
txt = open("threekingdoms.tx