
Python作为数据科学领域的主流语言,拥有一个庞大且活跃的生态系统,其中文本分析库尤为丰富。本文精选了15个功能强大、应用广泛的Python文本分析库,涵盖从预处理、分析到可视化的全流程,并附上使用说明、适用场景和代码示例,帮助高效挖掘文本中的数据。
import jieba
text = "自然语言处理是人工智能的重要方向。"
seg_list = jieba.cut(text, cut_all=False) # 精确模式
print("分词结果: " + "/ ".join(seg_list))
# 输出: 自然语言/ 处理/ 是/ 人工智能/ 的/ 重要/ 方向/ 。from snownlp import SnowNLP
s = SnowNLP("这部电影的剧情很棒,演员演技也在线!")
print(f"情感得分(越接近1越积极): {s.sentiments}")
# 输出可能为: 0.95...from cnsenti import Sentiment
senti = Sentiment()
result = senti.sentiment_count("今天天气真好,阳光明媚,让人心情愉悦。")
print(f"情绪词统计: {result}")
# 输出包含 {'好词': 2, '坏词': 0, ...}import nltk
nltk.download('punkt')
from nltk.tokenize import word_tokenize
text = "Natural Language Processing is fascinating."
tokens = word_tokenize(text)
print(f"英文分词: {tokens}")
# 输出: ['Natural', 'Language', 'Processing', 'is', 'fascinating', '.']import spacy
nlp = spacy.load("zh_core_web_sm") # 加载中文小模型
doc = nlp("苹果公司计划在2025年于上海开设新的研发中心。")
for ent in doc.ents:
print(f"实体: {ent.text}, 类别: {ent.label_}")
# 输出可能: 实体: 苹果公司, 类别: ORG
# 实体: 2025年, 类别: DATE
# 实体: 上海, 类别: GPEfrom gensim import corpora
from gensim.models import LdaModel
documents = [["苹果", "手机", "发布"],
["市场", "竞争", "激烈"],
["苹果", "公司", "利润", "增长"]]
dictionary = corpora.Dictionary(documents)
corpus = [dictionary.doc2bow(text) for text in documents]
lda = LdaModel(corpus=corpus, id2word=dictionary, num_topics=2)
print(lda.print_topics())
# 输出文档的潜在主题分布from textblob import TextBlob
blob = TextBlob("I love this product. It's amazing!")
print(f"情感极性: {blob.sentiment.polarity}") # 正值表示积极
# 输出可能: 0.5from transformers import pipeline
classifier = pipeline("sentiment-analysis")
result = classifier("I'm so excited to start this new project!")
print(result)
# 输出: [{'label': 'POSITIVE', 'score': 0.999...}]from pattern.en import sentiment
score = sentiment("This is a terrible idea.")
print(f"情感值: {score}") # 负值表示消极import textstat
text = "The cat sat on the mat."
flesch_score = textstat.flesch_reading_ease(text)
print(f"Flesch可读性分数: {flesch_score}") # 分数越高越易读import pandas as pd
import texthero as hero
df = pd.DataFrame({"text": ["Hello world!", "Python is great."]})
df['clean'] = hero.clean(df['text']) # 一键清洗(小写、去标点等)
print(df['clean'])# 启动doccano服务
docker run -d --name doccano -p 8000:8000 doccano/doccano
# 访问 http://localhost:8000 进行标注pip install label-studio
label-studio startfrom sklearn.feature_extraction.text import TfidfVectorizer
corpus = ['This is the first document.',
'This document is the second document.']
vectorizer = TfidfVectorizer()
X = vectorizer.fit_transform(corpus)
print(vectorizer.get_feature_names_out())
print(X.toarray()) # TF-IDF特征矩阵from wordcloud import WordCloud
import matplotlib.pyplot as plt
text = "Python data science machine learning deep learning AI Python"
wordcloud = WordCloud().generate(text)
plt.imshow(wordcloud, interpolation='bilinear')
plt.axis("off")
plt.show()掌握这些库,你便能从容应对从数据获取、清洗、分析到洞察呈现的完整文本分析任务。结合具体场景,灵活选用,让Python成为你解读文本世界的得力助手。
“无他,惟手熟尔”!有需要的用起来!
如果你觉得这篇文章有用,欢迎点赞、转发、收藏、留言、推荐❤!