gzj137070928 发表于 2020-11-10 13:36:42

文本词频统计

# 文本词频统计
# HamletV1:找一个哈姆雷特的文件,保存为hamlet.txt,放在同一目录里面
def getText(filename):
    txt = open(filename, "r").read()
    txt = txt.lower()
    for ch in '!@#$%^&*+-()[]{}<>=_:;\\‘’"|~.':
      txt = txt.replace(ch, " ")
    return txt

f_name = "hamlet.txt"
hamletTxt = getText(f_name)
words = hamletTxt.split()
counts = {}
for word in words:
    # word之前没有则创建初始值为0,然后逐次加1
    counts = counts.get(word, 0) + 1
items = list(counts.items())
items.sort(key=lambda x:x,reverse=True)
# 将出现次数最多的前十个词输出
for i in range(10):
    word, count = items
    print("{0:<10}{1:>5}".format(word, count))
页: [1]
查看完整版本: 文本词频统计