python评论词频统计结果保存为文件
时间: 2023-09-19 13:13:26 浏览: 45
要将Python评论词频统计结果保存到文件中,可以使用Python内置的文件操作函数。以下是一个简单的代码示例:
```python
from collections import Counter
# 读取评论数据
with open('comments.txt', 'r') as f:
comments = f.read()
# 分词统计
words = comments.split()
word_freq = Counter(words)
# 保存到文件
with open('word_freq.txt', 'w') as f:
for word, freq in word_freq.most_common():
f.write(f'{word}: {freq}\n')
```
这个代码示例假设评论数据已经保存在一个名为 `comments.txt` 的文件中。代码首先读取评论数据,然后使用 Python 的 `split()` 函数将其分词,并使用 `Counter` 对象进行词频统计。最后,代码将统计结果保存到名为 `word_freq.txt` 的文件中。
在保存文件时,我们使用了 `most_common()` 方法来获取词频最高的单词。这个方法返回一个包含元组的列表,每个元组包含单词和对应的词频。我们使用 `f.write()` 函数将每个元组写入文件中。
相关问题
蒙古文词频统计结果放到文件夹python
以下是一个将蒙古文文本进行词频统计并将结果保存到文件的 Python 代码示例:
```python
import re
from collections import Counter
def countWords(text):
# 分词
words = re.findall(r'\b\w+\b', text)
# 统计词频
freq = Counter(words)
return freq
def saveToFile(freq, filepath):
with open(filepath, 'w', encoding='utf-8') as f:
for word, count in freq.items():
f.write(word + '\t' + str(count) + '\n')
# 示例
mongolian_text = 'Монгол улсын их сургуулийн нэр төр. Монгол улсын их сургуулийн нэр төр.'
freq = countWords(mongolian_text)
saveToFile(freq, 'word_freq.txt')
```
在这个示例中,我们先对蒙古文文本进行词频统计,然后将统计结果保存到文件 'word_freq.txt' 中。文件中每一行包含一个单词和它的词频,中间用制表符分隔。
如果需要处理多个文本并将它们的词频统计结果保存到不同的文件中,可以使用一个循环来遍历文件列表并对每个文件进行处理。例如:
```python
filepaths = ['text1.txt', 'text2.txt', 'text3.txt']
for filepath in filepaths:
with open(filepath, 'r', encoding='utf-8') as f:
text = f.read()
freq = countWords(text)
saveToFile(freq, filepath + '.freq')
```
这个示例中,我们先定义一个文件列表 filepaths,然后使用一个循环遍历列表中的每个文件并对它们进行词频统计。将每个文件的词频统计结果保存到以文件名加上 '.freq' 后缀的文件中。
Python文件 文本词频统计代码
以下是Python实现文本词频统计的代码:
```python
import re
# 定义函数,传入文件名和要统计的单词个数
def word_count(file_name, num):
# 打开文件
with open(file_name, 'r') as f:
# 读取文件内容
content = f.read()
# 将单词转换为小写,并去掉标点符号
words = re.findall(r'\b[a-z]+\b', content.lower())
# 统计单词出现的次数
word_dict = {}
for word in words:
if word not in word_dict:
word_dict[word] = 1
else:
word_dict[word] += 1
# 排序并输出结果
sorted_word_dict = sorted(word_dict.items(), key=lambda x: x[1], reverse=True)
for i in range(num):
print(sorted_word_dict[i][0], sorted_word_dict[i][1])
# 调用函数进行测试
word_count('test.txt', 10)
```
代码解释:
1. `re.findall(r'\b[a-z]+\b', content.lower())` 用正则表达式匹配文件内容中的单词,`\b` 表示单词的边界,`[a-z]+` 表示一个或多个小写字母。
2. `word_dict` 用字典来保存单词出现的次数,如果单词不存在则添加到字典中,否则将出现次数加一。
3. `sorted_word_dict` 将字典按照值进行排序,`key=lambda x: x[1]` 表示按照值进行排序,`reverse=True` 表示降序排列。
4. `for i in range(num)` 只输出前面 num 个单词和出现次数。