编写一个 Python 程序,读取data.txt文件中的文本,对进行分词,统计频率最高的前100个,结果输出到result.csv文件中。
时间: 2023-11-22 07:55:20 浏览: 49
以下是代码实现,需要安装nltk库和pandas库:
```python
import nltk
import pandas as pd
# 读取文件
with open('data.txt', 'r', encoding='utf-8') as f:
text = f.read()
# 分词
tokens = nltk.word_tokenize(text)
# 去除标点符号和停用词
stop_words = set(nltk.corpus.stopwords.words('english'))
words = [word.lower() for word in tokens if word.isalpha() and word.lower() not in stop_words]
# 统计频率
freq_dist = nltk.FreqDist(words)
# 输出前100个到CSV文件
df = pd.DataFrame(freq_dist.most_common(100), columns=['Word', 'Frequency'])
df.to_csv('result.csv', index=False)
```
其中,我们使用了NLTK库进行分词和停用词过滤,并使用Pandas库将结果输出到CSV文件中。
相关问题
用以下的代码编写一个 Python 程序,读取data.txt文件中的文本,对进行分词,统计频率最高的前100个,结果输出到result.csv文件中。
以下是代码实现:
```python
import jieba
import csv
# 读取文件
with open('data.txt', 'r', encoding='utf-8') as f:
text = f.read()
# 分词
words = jieba.cut(text)
# 统计词频
freq = {}
for word in words:
if len(word) > 1:
freq[word] = freq.get(word, 0) + 1
# 排序,取前100个
top100 = sorted(freq.items(), key=lambda x: x[1], reverse=True)[:100]
# 结果写入CSV文件
with open('result.csv', 'w', encoding='utf-8', newline='') as f:
writer = csv.writer(f)
writer.writerow(['词语', '频率'])
for word, count in top100:
writer.writerow([word, count])
```
首先使用`open()`函数读取`data.txt`文件中的文本内容,然后使用`jieba`库对文本进行分词,得到分词后的列表`words`。接着使用一个字典`freq`来统计每个词在文本中出现的次数。由于有些单字词会干扰结果,因此我们在统计词频时只考虑长度大于1的词。
统计完词频后,我们将字典`freq`按照值降序排序,取前100个最高频的词,得到一个列表`top100`。最后,将`top100`写入CSV文件`result.csv`中,格式为两列:词语和频率。
读取 data.txt 文件并借助 jieba 库实现词频统计, 将出现频率最高的 10 个词输出
好的,我可以帮你实现这个功能。首先需要安装`jieba`库,可以使用以下命令进行安装:
```
pip install jieba
```
然后我们可以编写以下代码读取`data.txt`文件并进行词频统计:
```python
import jieba
# 读取文件内容
with open('data.txt', 'r', encoding='utf-8') as f:
content = f.read()
# 进行分词
words = jieba.cut(content)
# 统计词频
word_count = {}
for word in words:
if len(word) > 1: # 只统计长度大于1的词
if word in word_count:
word_count[word] += 1
else:
word_count[word] = 1
# 输出出现频率最高的前10个词
top_words = sorted(word_count.items(), key=lambda x: x[1], reverse=True)[:10]
for word, count in top_words:
print(word, count)
```
以上代码首先使用`open()`函数读取`data.txt`文件的内容,然后使用`jieba.cut()`函数对内容进行分词。接着使用一个字典`word_count`统计每个词出现的次数,最后使用`sorted()`函数对字典进行排序,输出出现频率最高的前10个词。