利用python进行词频统计并将结果打印到另一个文档中
时间: 2023-05-19 07:06:19 浏览: 92
你可以使用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程序,用于对文本文件进行词频统计:
```python
import string
def word_count(file_path):
with open(file_path, 'r') as f:
text = f.read().lower()
# 将所有字符转换为小写,方便统计
# 如果需要区分大小写,可以删除上一行
# 删除标点符号
text = text.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
# 按单词出现次数从大到小排序
word_count = sorted(word_count.items(), key=lambda x: x[1], reverse=True)
return word_count
# 示例用法
if __name__ == '__main__':
file_path = 'test.txt'
result = word_count(file_path)
for word, count in result:
print(word, count)
```
该程序可以读取指定路径下的文本文件,统计其中每个单词出现的次数,并按照单词出现次数从大到小排序,最后输出每个单词及其出现次数。该程序使用了Python的标准库函数,不需要额外安装任何第三方库。
基于python将csv文件词频统计并将结果存入txt文件中
可以使用Python内置的csv和collections模块来进行词频统计,并使用Python内置的文件操作函数将结果存入txt文件中。以下是一个示例代码:
```python
import csv
from collections import Counter
# 读入csv文件
with open('data.csv', 'r') as f:
reader = csv.reader(f)
data = list(reader)
# 将所有单词合并成一个字符串
text = ' '.join([' '.join(row) for row in data])
# 将字符串按空格分割成单词列表
words = text.split()
# 使用Counter统计词频
word_counts = Counter(words)
# 将结果写入txt文件
with open('result.txt', 'w') as f:
for word, count in word_counts.most_common():
f.write('{} {}\n'.format(word, count))
```
其中,`data.csv`是需要统计的csv文件的文件名,`result.txt`是结果存入的txt文件的文件名。这段代码将读入csv文件中的所有单元格,将它们合并成一个字符串,然后按空格分割成单词列表,最后使用Counter统计每个单词出现的次数。然后,将结果写入txt文件中,每一行写入一个单词及其出现次数,用空格分隔。