怎么用pandas统计文章中每个单词出现的次数
时间: 2023-09-10 18:15:05 浏览: 44
我们可以将文章中每个单词转换成小写,并使用pandas中的Series对象来统计每个单词出现的次数。以下是代码示例:
```python
import pandas as pd
# 读取文章内容
with open('article.txt', 'r') as f:
content = f.read()
# 将文章中的标点符号去除
content = ''.join(c for c in content if c.isalnum() or c.isspace())
# 将文章中的单词转换成小写
words = content.lower().split()
# 使用pandas的Series对象统计每个单词出现的次数
word_counts = pd.Series(words).value_counts()
print(word_counts)
```
在上述代码中,我们首先读取文章内容,并去除了文章中的标点符号。接着,我们将文章中的单词转换成小写,并使用pandas的Series对象来进行统计。最后,我们输出了每个单词出现的次数。
相关问题
制定任意英文文章的文本文件,使用pandas统计文章中每个单词出现的次数,保留数字,连字符,撇号,统计结果按照出现次数降序再按照单词字典序排序,将统计结果保存到csv文件中,并使用水平柱状图显示出现次数最多的十个单词
以下是一个例子,可以根据需要进行修改:
```python
import pandas as pd
import matplotlib.pyplot as plt
# 读取文本文件
with open('example.txt', 'r') as f:
text = f.read()
# 将文本转换为小写并移除标点符号
text = text.lower()
text = text.replace('-', ' ')
text = text.replace("'", '')
text = ''.join(c for c in text if c.isalnum() or c.isspace())
# 将文本拆分为单词列表
words = text.split()
# 统计每个单词出现的次数
word_counts = {}
for word in words:
if word in word_counts:
word_counts[word] += 1
else:
word_counts[word] = 1
# 将统计结果转换为DataFrame并按照要求排序
df = pd.DataFrame.from_dict(word_counts, orient='index', columns=['count'])
df = df.sort_values(by=['count', df.index.name], ascending=[False, True])
# 保存统计结果到csv文件
df.to_csv('word_counts.csv')
# 绘制水平柱状图
top_words = df.head(10)
plt.barh(top_words.index, top_words['count'])
plt.xlabel('Count')
plt.ylabel('Word')
plt.title('Top 10 Words by Count')
plt.show()
```
注意,这只是一个简单的例子,实际使用时可能需要考虑更多的情况,例如处理缩写、停用词等。
制定任意英文文章的文本文件,使用pandas统计文章中每个单词出现的次数,保留形如“60”的数字、形如“self- distrust”中间的连字符、形如“isn‘t”中间的撇号,统计结果按照出现次数降序再按照单词字典序排序,将统计结果保存到csv文件中,并使用水平柱状图显示出现次数最多的十个单词
以下是一个示例代码,实现了上述要求:
```python
import pandas as pd
import re
import matplotlib.pyplot as plt
# 读入文本文件
with open('article.txt', 'r') as f:
text = f.read()
# 使用正则表达式分词
words = re.findall(r'\d+|\w+(?:-\w+)*|\w+(?:\'\w+)*', text)
# 统计单词出现次数
word_counts = pd.Series(words).value_counts().sort_values(ascending=False)
# 保存到csv文件
word_counts.to_csv('word_counts.csv', header=['count'])
# 取前十个单词作为水平柱状图的数据
top_words = word_counts.head(10)
plt.barh(top_words.index, top_words.values)
plt.gca().invert_yaxis()
plt.show()
```
需要注意的是,这里使用了正则表达式对文本进行分词,分别匹配了数字、带连字符的单词以及带撇号的单词。统计单词出现次数时,使用了pandas的Series对象,方便进行排序和保存到csv文件。最后,使用matplotlib库绘制水平柱状图展示出现次数最多的前十个单词。