以下是一个示例代码,用于按照频率对文本文件中的单词进行排序:
from collections import Counter
# 打开文本文件并读取内容
with open('input.txt', 'r') as file:
text = file.read().lower()
# 将文本内容按照非字母字符进行分割
words = re.findall(r'\b\w+\b', text)
# 使用Counter计算单词的频率
word_freq = Counter(words)
# 按照频率对单词进行排序
sorted_words = sorted(word_freq.items(), key=lambda x: x[1], reverse=True)
# 打印排序结果
for word, freq in sorted_words:
print(word, freq)
在上述代码中,我们首先打开并读取文本文件的内容。然后,使用正则表达式将文本内容按照非字母字符进行分割,得到单词列表。接下来,利用Counter
类计算每个单词的频率。最后,使用sorted
函数对单词按照频率进行排序,并打印排序结果。