python文本数据分析60行以上例子
时间: 2023-07-03 12:28:16 浏览: 57
以下是一个 Python 文本数据分析的完整例子,它可以读取一个文本文件并进行一系列的数据清洗、分析和可视化。这个例子代码共计 63 行,包含了使用 pandas、matplotlib、seaborn 等库进行数据处理和可视化的示例。
```python
# 导入必要的库
import re
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
# 读取文本文件
with open('text_file.txt', 'r') as f:
text = f.read()
# 将文本分割成单词列表
words = re.findall('\w+', text.lower())
# 计算每个单词出现的次数
word_counts = pd.Series(words).value_counts()
# 去除停用词
stopwords = ['the', 'and', 'to', 'of', 'in', 'that', 'it', 'with', 'for', 'on', 'at', 'this', 'from', 'by', 'an', 'but', 'be', 'or', 'not', 'such', 'which', 'was', 'were']
word_counts = word_counts.drop(stopwords)
# 输出出现次数最高的前二十个单词及其出现次数
top_words = word_counts.head(20)
print(top_words)
# 绘制词频分布图
plt.figure(figsize=(10, 6))
sns.barplot(x=top_words.values, y=top_words.index)
plt.title('Word Frequency Distribution')
plt.xlabel('Frequency')
plt.ylabel('Word')
plt.tight_layout()
plt.show()
```
这个例子代码中,我们首先读取了一个文本文件并将其分割成单词列表。然后使用 pandas 库中的 Series 类型进行单词计数,并通过 drop() 方法去除了一些常见的停用词。接着输出了出现频率最高的前二十个单词,并使用 seaborn 库绘制了一个词频分布图。