打开一个文本,写一个词频统计,按照倒序排的python代码
时间: 2024-02-26 21:56:28 浏览: 20
好的,以下是Python的词频统计,按照倒序排列的代码:
```python
from collections import Counter
# 打开文本文件
with open("text.txt", "r") as file:
# 读取文件内容
text = file.read()
# 去除标点符号和换行符
text = text.lower().replace("\n", " ").translate(str.maketrans("", "", string.punctuation))
# 分离单词
words = text.split()
# 统计单词频率
word_freq = Counter(words)
# 按照倒序排列
sorted_word_freq = sorted(word_freq.items(), key=lambda x: x[1], reverse=True)
# 输出结果
for word, freq in sorted_word_freq:
print(word, freq)
```
这段代码会读取一个名为 `text.txt` 的文本文件,统计其中所有单词的出现频率,并按照倒序排列输出结果。请注意,这段代码没有使用任何外部库,只使用了 Python 内置的 `collections` 库。
相关问题
写一个哈姆雷特词频统计python代码
以下是一个简单的哈姆雷特词频统计 Python 代码示例:
```
import string
# 打开文本文件并读取内容
with open('hamlet.txt', 'r') as file:
text = file.read()
# 将文本转换为小写并去除标点符号
text = text.lower().translate(str.maketrans('', '', string.punctuation))
# 将文本拆分为单词列表
words = text.split()
# 创建一个空字典来存储单词计数
word_count = {}
# 遍历单词列表并计数每个单词出现的次数
for word in words:
if word in word_count:
word_count[word] += 1
else:
word_count[word] = 1
# 按单词出现次数从高到低排序并打印结果
for word, count in sorted(word_count.items(), key=lambda x: x[1], reverse=True):
print(f'{word}: {count}')
```
在这个示例代码中,我们首先使用 Python 的 `with` 语句打开并读取了一个名为 `hamlet.txt` 的文本文件。然后,我们将文本转换为小写并去除标点符号,这样可以使单词的计数更加准确。接着,我们使用 `split()` 方法将文本拆分为单词列表,并创建一个空字典来存储单词计数。最后,我们遍历单词列表并对每个单词计数,最终按单词出现次数从高到低排序并打印结果。
写一个哈姆雷特词频统计Python代码
以下是一个简单的Python代码,用于对哈姆雷特文本进行词频统计:
```python
import string
# 打开文本文件并读取内容
with open('hamlet.txt', 'r') as file:
text = file.read()
# 将文本转换为小写并删除标点符号
text = text.lower()
text = text.translate(str.maketrans('', '', string.punctuation))
# 将文本拆分为单个单词
words = text.split()
# 创建一个空字典来存储每个单词的出现次数
word_counts = {}
# 计算每个单词的出现次数并将其存储在字典中
for word in words:
if word not in word_counts:
word_counts[word] = 1
else:
word_counts[word] += 1
# 按出现次数从高到低对单词进行排序
sorted_words = sorted(word_counts.items(), key=lambda x: x[1], reverse=True)
# 输出前10个单词及其出现次数
for word, count in sorted_words[:10]:
print(word, count)
```
请注意,此代码假定文本文件名为`hamlet.txt`。您需要将文件名替换为您自己的文本文件名。此外,此代码仅考虑单个单词,因此可能无法正确处理某些单词形式(例如名词的复数形式或动词的时态形式)。