以下是 Python 代码实现,统计英文文本中单词出现的次数,并将结果按降序输出:

import re
from collections import Counter

# 读取文本文件
with open('text.txt', 'r') as f:
    text = f.read()

# 将文本中的非字母字符替换为空格
text = re.sub('[^a-zA-Z]', ' ', text)

# 将文本转换为小写
text = text.lower()

# 分割文本为单词列表
words = text.split()

# 使用collections.Counter统计单词出现次数
word_counts = Counter(words)

# 按降序输出单词及其出现次数
for word, count in word_counts.most_common():
    print(word, count)

其中,'text.txt'是要统计的文本文件路径。代码首先读取文本文件内容,并将非字母字符替换为空格,然后将文本转换为小写,最后使用collections.Counter统计单词出现次数,并按降序输出。

Python 代码统计英文单词出现次数并按降序输出

原文地址: https://www.cveoy.top/t/topic/jPoH 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录