python文本分析代码,找出高频出现的词语
时间: 2025-06-04 14:23:21 浏览: 13
### Python 实现文本分析代码以统计高频词
以下是基于 Python 的一段完整代码,能够实现对给定文本的高频词统计功能。此代码综合运用了 `pandas`、`jieba` 和 `collections.Counter` 等工具[^3]。
#### 完整代码示例
```python
import pandas as pd
from collections import Counter
import jieba
# 读取 Excel 文件中的文本数据
df = pd.read_excel(r"example.xlsx") # 替换为实际文件路径
text_column = df['Text'] # 假设文本存储在名为 'Text' 的列中
# 将所有单元格中的文本合并成单个字符串
all_text = "".join(text_column.dropna()) # 删除缺失值后再拼接
# 使用结巴分词进行中文分词
words = jieba.lcut(all_text)
# 统计词频
word_count = Counter(words)
# 排序并转换为 DataFrame
word_count_df = pd.DataFrame(list(word_count.items()), columns=['Word', 'Frequency'])
word_count_df = word_count_df[word_count_df['Word'].str.len() > 1] # 可选:过滤掉长度小于等于1的词
word_count_df = word_count_df.sort_values(by='Frequency', ascending=False).reset_index(drop=True)
# 输出前 20 个高频词
print(word_count_df.head(20))
# 保存结果至新的 Excel 文件
word_count_df.to_excel(r"output_word_frequency.xlsx", index=False)
```
以上代码适用于处理包含中文字符的文本数据,并利用 `jieba` 库完成分词操作。如果目标是英文或其他无需分词的语言,则可以直接跳过分词部分,仅保留基础的单词分割逻辑[^2]。
---
#### 英文文本处理优化版本
对于纯英文文本,可采用如下简化方法:
```python
import re
from collections import Counter
def count_words_in_english(text):
# 清洗文本并拆分为单词列表
words = re.findall(r'\b\w+\b', text.lower())
# 计算词频
word_counts = Counter(words)
return word_counts
# 示例输入
sample_text = """
Natural language processing (NLP) is a field of computer science, artificial intelligence,
and linguistics concerned with the interactions between computers and human languages.
"""
# 调用函数
result = count_words_in_english(sample_text)
for word, freq in result.most_common(10): # 显示最常见的10个单词及其频率
print(f"{word}: {freq}")
```
该脚本通过正则表达式清洗和标准化文本后,调用了 `Counter` 类快速生成词频分布表[^2]。
---
#### 关键技术点说明
- **分词工具**:针对中文场景推荐使用第三方库 `jieba` 来提高准确性;而英文环境下可通过简单的正则匹配分离单词[^3]。
- **停用词过滤**:为了更精确地反映主题内容,在正式项目中通常还需要引入一份自定义或通用的停用词表(stopwords),从而剔除诸如 “the”, “is” 或者 “之”,“于” 这样的常见虚词[^1]。
- **性能考量**:当面对超大规模语料时,建议考虑分布式计算框架如 Spark Streaming 结合 PySpark API 提升效率。
---
阅读全文
相关推荐



















