Python案例:词频统计

一、提出任务

统计文本文件里单词出现次数。

二、完成任务

1、创建文本文件test.txt

Python案例:词频统计_第1张图片

2、创建Python项目PythonWordCount

file = open("test.txt", "r")
words = []
for line in file:
    for word in line.replace('\n', '').split(" "):
        words.append(word)

map = {}
for word in words:
    map[word] = map[word] + 1 if word in map.keys() else 1

for key in map:
    print(key + ": " + str(map[key]))

3、运行程序,查看结果

Python案例:词频统计_第2张图片

你可能感兴趣的:(Python编程)