Python知识点:利用TextBlob实现自然语言处理

552 阅读3分钟

简明介绍

TextBlob是一个用于处理文本数据(textual data)的Python库。TextBlob是基于NLTKPattern的英文文本处理工具包,用于深入研究常见的自然语言处理 (Natural Language Processing,NLP) 任务,例如词性标注、名词短语提取、情感分析、分类、翻译等。

  • 标记化(Tokenization):将文本拆分为单词(words属性)和句子(sentences属性)
  • 词性标注(Part-of-Speech Tagging,POS):给每个词语标注词类标签(tags属性),如动词、名词、形容词等
  • 名词短语提取(Noun Phrase Extraction):识别文本中的名词短语(noun_phrases属性)
  • 词频统计(Word and Phrase Frequencies):确定词语出现的频率(word_counts属性)
  • 单词变形(Word Inflection):将名词的复数变为单数(singularize方法),将单数变为复数(pluralize方法)
  • 词形还原(Word Lemmatization):将词语转化为基本形式(lemmatize方法)
  • 拼写校正(Spelling Correction):correct方法
  • 情感分析(Sentiment Analysis):识别文本中的情感倾向(sentiment属性),如积极、消极或中性
  • 分析(Parsing):parse方法
  • 分类(Classification):朴素贝叶斯(Naive Bayes),决策树(Decision Tree)
  • 集成WordNet:WordNet是普林斯顿大学创建的一个单词数据库,能够查找单词定义,并获取其同义词和反义词。

环境安装

# 安装模块
$ pip install -U textblob
# 下载语料库(NLTK corpora)
$ python -m textblob.download_corpora
# 启动NLTK下载器
$ python -c "import nltk; nltk.download()"
# 下载指定语料库
$ python -c "import nltk; nltk.download('punkt_tab')"
$ python -c "import nltk; nltk.download('averaged_perceptron_tagger_eng')"
# 安装扩展
$ pip install textblob-aptagger

NLTK语料库

  • Brown Corpus(出自布朗大学):用于词性标注
  • Punkt:用于英文句子分词
  • WordNet:用于单词的定义、同义词和反义词
  • Averaged Perceptron Tagger:用于词性标注
  • conll2000:用于组块分析,将文本分成组块,如名词、动词、名词短语等。conll2000的名字的取自“Conference on Computational Natural Language Learning”,conll2000语料库由该会议推出
  • Movie Reviews:用于情感分析

应用示例

#!/usr/bin/env python3

from textblob import TextBlob
from textblob import Word

text = "Today is a beautiful day. Tomorrow looks like bad weather."

# 标记化
def tokenize(text):
    b = TextBlob(text)
    # 分词:WordList对象(删除标点符号后的Word对象列表)
    # 分句:Sentence对象列表
    print(b.words, b.sentences)

tokenize(text)

# 词性标注
def posTag(text):
    b = TextBlob(text)
    # 词性元组列表,每个元组包含单词和表示其词性的字符串
    print(b.tags)

posTag(text)

# 名词短语提取
def nounPhrasesExtract(text):
    b = TextBlob(text)
    # WordList对象
    print(b.noun_phrases)

nounPhrasesExtract(text)

# 词频统计
def wordFrequency(text, key, wordOrPhrase):
    b = TextBlob(text)
    if wordOrPhrase:
        print(b.word_counts[key], b.words.count(key))
    else:
        print(b.noun_phrases.count(key))

wordFrequency(text, "tomorrow", True)
wordFrequency(text, "bad weather", False)

# 单词变形
def wordInflect(text, singular):
    w = Word(text)
    if singular:
        print(w.pluralize())
    else:
        print(w.singularize())

wordInflect("person", True)
wordInflect("indices", False)

# 词形还原
def wordLemmatize(text):
    w = Word(text)
    print(w.lemmatize())

wordLemmatize("varieties")

# 拼写校正
def spellCorrectOfWord(text):
    w = Word(text)
    print(w.correct())

def spellCorrectOfBlob(text):
    b = TextBlob(text)
    print(b.correct())

spellCorrectOfWord("havv")
spellCorrectOfBlob("I havv goood speling!")

# 情感分析
def sentimentAnalyze(text):
    b = TextBlob(text)
    # Sentiment对象,polarity表示极性,-1.0(消极)到1.0(积极),0.0为中性。subjectivity表示主观性,0.0(客观)到1.0(主观)
    print(b.sentiment)

sentimentAnalyze(text)

# 解析
def parse(text):
    b = TextBlob(text)
    print(b.parse())

parse(text)

# 集成WordNet
def wordNet(text):
    w = Word(text)
    # 单词定义列表
    # 单词同义词集合
    print(w.definitions, w.synsets)

wordNet("happy")

说明1:创建TextBlob对象时可以指定算法以适应特定类型的文本。

class TextBlob(text, tokenizer=None, pos_tagger=None, np_extractor=None, analyzer=None, parser=None, classifier=None, clean_html=False)
参数说明
tokenizer:WordTokenizer、SentenceTokenizer
pos_tagger:PatternTagger、NLTKTagger
np_extractor:FastNPExtractor、ConllExtractor
analyzer:PatternAnalyzer、NaiveBayesAnalyzer
parser:PatternParser
classifier:BaseClassifier(基本分类器)、DecisionTreeClassifier(决策树分类器)、MaxEntClassifier(最大熵分类器)、NLTKClassifier(NLTK分类器)、NaiveBayesClassifier(朴素贝叶斯分类器)、PositiveNaiveBayesClassifier(正向朴素贝叶斯分类器)

说明2:TextBlob类支持字符串处理方法,可以与字符串进行比较,为多种NLP任务提供支持。Sentence、Word和TextBlob类都继承自BaseBlob类,因此它们有很多共同的方法和属性。

class TextBlob(text, tokenizer=None, pos_tagger=None, np_extractor=None, analyzer=None, parser=None, classifier=None, clean_html=False)
class Sentence(sentence, start_index=0, end_index=None, *args, **kwargs)
class Word(string, pos_tag=None)
class WordList(collection)

参考资料

sloria/TextBlob: Simple, Pythonic, text processing

TextBlob: Simplified Text Processing

《Python程序设计:人工智能案例实践》