Python统计文件中词出现的频率,非常简单,专业人士就不要点了

兄弟们,今天咱们用Python来统计文件中词出现的频率。

你需要准备

  • Python
  • pycharm
  • 准备好的txt文件

知识点

  • 文件读写
  • 基础语法
  • 字符串处理
  • 循环遍历

代码展示

# 导入系统包
import platform

print("发奋忘食,乐以忘优,不知老之将至")
print("Python统计文件中词出现的频率 \n")


def count_words(filepath):
    with open(filepath, encoding="utf8") as file:
        # file.read()读取文件的所有内容
        string = file.read()
        # str.split(" ")按空格分割
        string_list = string.split(" ")
        return len(string_list)


# 调用函数读取文件统计单词数
print(count_words("./py022.txt"))

print("你当前使用的Python 版本是", platform.python_version())

我现在也不知道到底有多少个单词,疯狂复制了一通。

让我们运行一下,看看到底有多少单词量。


好家伙,这不比我自己数快多了,大家可以替换成自己想要的词汇,快去试试吧~

猜你喜欢

转载自blog.csdn.net/ooowwq/article/details/125995217