实战:Python + TextBlob 英文文本情感分析与纠错

TextBlob 是一个强大的 Python 库,可快速实现英文文本的情感分析(Sentiment Analysis)和拼写纠错(Spelling Correction)。以下是完整实现步骤:


1. 环境准备

安装依赖库:

pip install textblob
python -m textblob.download_corpora  # 下载语料库


2. 情感分析

情感极性(Polarity)范围:$[-1.0, 1.0]$,其中 $-1$ 为极端负面,$1$ 为极端正面。
主观性(Subjectivity)范围:$[0.0, 1.0]$,$0$ 表示完全客观,$1$ 表示完全主观。

from textblob import TextBlob

def analyze_sentiment(text):
    blob = TextBlob(text)
    polarity = blob.sentiment.polarity
    subjectivity = blob.sentiment.subjectivity
    
    # 判断情感倾向
    if polarity > 0.2:
        sentiment = "积极"
    elif polarity < -0.2:
        sentiment = "消极"
    else:
        sentiment = "中性"
    
    print(f"文本: {text}")
    print(f"情感极性: {polarity:.2f} ({sentiment})")
    print(f"主观性: {subjectivity:.2f}\n")

# 测试
analyze_sentiment("I love this product! It's amazing.")
analyze_sentiment("The service was terrible and slow.")
analyze_sentiment("The meeting starts at 9 AM.")

输出示例

文本: I love this product! It's amazing.
情感极性: 0.62 (积极)
主观性: 0.65

文本: The service was terrible and slow.
情感极性: -0.80 (消极)
主观性: 0.75

文本: The meeting starts at 9 AM.
情感极性: 0.00 (中性)
主观性: 0.00


3. 拼写纠错

通过 correct() 方法自动修正拼写错误:

def correct_spelling(text):
    blob = TextBlob(text)
    corrected = blob.correct()
    print(f"原始文本: {text}")
    print(f"修正结果: {corrected}\n")

# 测试
correct_spelling("I am hapy to see yu!")
correct_spelling("Ths librry is awesum.")

输出示例

原始文本: I am hapy to see yu!
修正结果: I am happy to see you!

原始文本: Ths librry is awesum.
修正结果: The library is awesome.


4. 高级应用:批量处理文件

处理 data.txt 文件中的多行文本:

def process_file(filename):
    with open(filename, 'r') as file:
        for line in file:
            line = line.strip()
            if line:  # 跳过空行
                blob = TextBlob(line)
                corrected = blob.correct()
                polarity = blob.sentiment.polarity
                
                print(f"原始: {line}")
                print(f"修正: {corrected}")
                print(f"情感: {polarity:.2f}\n")

# 使用示例
process_file("data.txt")


5. 关键注意
  • 情感分析局限:对讽刺、复杂句式可能判断不准(如 "What a wonderful day... to stay in bed!")
  • 纠错原理:基于统计语言模型,优先常见单词组合
  • 性能优化:长文本可分段处理(TextBlob(text).split())

通过 TextBlob,10 行代码即可完成英文文本的情感判断与智能纠错,适合评论分析、内容审核等场景。

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐