python统计所给文档中出现的当次词频并打印到新的文档中
时间: 2023-05-19 22:06:20 浏览: 66
可以使用Python中的collections模块中的Counter类来实现统计词频的功能,具体代码如下:
```python
from collections import Counter
# 读取原始文档
with open('input.txt', 'r', encoding='utf-8') as f:
text = f.read()
# 统计词频
words = text.split()
word_count = Counter(words)
# 将词频结果输出到新文档
with open('output.txt', 'w', encoding='utf-8') as f:
for word, count in word_count.items():
f.write(f'{word}: {count}\n')
```
这段代码会将原始文档中出现的每个单词的词频统计出来,并将结果输出到新的文档中。你可以将代码中的'input.txt'和'output.txt'替换成你自己的文件名。
相关问题
利用python进行词频统计并将结果打印到另一个文档中
你可以使用Python中的collections模块来进行词频统计,具体代码如下:
```python
import collections
# 读取文本文件
with open('input.txt', 'r') as f:
text = f.read()
# 将文本分词并统计词频
words = text.split()
word_counts = collections.Counter(words)
# 将结果写入另一个文本文件
with open('output.txt', 'w') as f:
for word, count in word_counts.most_common():
f.write(f'{word}: {count}\n')
```
其中,input.txt是需要进行词频统计的文本文件,output.txt是统计结果需要写入的文本文件。你可以根据需要修改文件名和路径。
Python编写实现统计哈姆雷特文档词频的功能,要求不统计虚词,打印出词频最高的前十个
好的,以下是实现代码:
```python
import re
from collections import Counter
# 读取文件内容
with open('hamlet.txt', 'r', encoding='utf-8') as f:
text = f.read()
# 定义虚词列表
stopwords = ['the', 'and', 'to', 'of', 'in', 'that', 'is', 'with', 'not', 'you', 'this', 'be', 'it', 'but', 'as', 'he', 'for', 'his', 'have', 'which', 'from', 'or', 'by', 'they', 'their', 'we', 'an', 'my', 'one', 'all', 'her', 'she', 'him', 'if', 'there', 'on', 'do', 'at', 'so', 'up', 'out', 'about', 'what', 'who', 'into', 'than', 'them', 'then', 'some', 'would', 'could', 'no', 'been', 'when', 'now', 'did', 'may', 'shall', 'such', 'our', 'yet', 'must']
# 利用正则表达式去除标点符号
text = re.sub(r'[^\w\s]', '', text)
# 将文本分割为单词列表
words = text.lower().split()
# 去除虚词
words = [word for word in words if word not in stopwords]
# 统计词频
word_counts = Counter(words)
# 打印出词频最高的前十个
for word, count in word_counts.most_common(10):
print(word, count)
```
其中,我们使用了正则表达式去除了标点符号,然后将文本分割为单词列表,并去除了虚词。最后,我们使用 `Counter` 类统计词频,再使用 `most_common` 方法打印出词频最高的前十个。