NLP人工智能【免费下载链接】TextBlobSimple, Pythonic, text processing--Sentiment analysis, part-of-speech tagging, noun phrase extraction, translation, and more.项目地址https://gitcode.com/gh_mirrors/te/TextBlob点击查看免费下载TextBlob 是一个面向 Python 的简化文本处理库它把常见的自然语言处理NLP任务封装成接近字符串操作的直觉式 API覆盖词性标注、名词短语提取、情感分析、文本分类等核心场景。本文以仓库根目录的 README.rst 为主线结合 src/textblob 源码与 docs/quickstart.rst 教程讲解从安装、语料准备到各功能模块的完整用法读完后你将能够用十几行代码搭建起一套可运行的中文/英文文本分析流水线。项目概览用 Pythonic 的方式做 NLP按照 README.rst 的定义TextBlob 是一个用于处理文本数据的 Python 库它围绕常见 NLP 任务提供简洁 API例如词性标注part-of-speech tagging名词短语提取noun phrase extraction情感分析sentiment analysis文本分类classification以及其他更多任务它的设计哲学可以用一句话概括把TextBlob对象当作学会了 NLP 的 Python 字符串来使用详见 docs/quickstart.rst 的引言。你既可以用它做一次性探索也可以把它嵌入到更大的文本处理工程中。在技术底座上README 明确指出TextBlob stands on the giant shoulders of NLTK and pattern, and plays nicely with both.——TextBlob 站在 NLTK 与 pattern 两大库的肩膀上并且与二者都能良好协作。从源码看这一表述是准确的词性标注、分词、词形还原、分类算法直接封装 NLTK 的实现例如 src/textblob/taggers.py 中的NLTKTagger、src/textblob/tokenizers.py 中的WordTokenizer/SentenceTokenizer情感分析、解析器、拼写纠正则移植自 pattern 库的英文实现位于 src/textblob/en/init.py该文件开头注明This file is based on pattern.en. See the bundled NOTICE file for license information.。核心特性清单README 官方列出的特性如下本文后续章节将逐一展开并给出源码依据名词短语提取Noun phrase extraction词性标注Part-of-speech tagging情感分析Sentiment analysis分类朴素贝叶斯Naive Bayes、决策树Decision Tree分词将文本切分为词与句子Tokenization词与短语频率统计Word and phrase frequencies句法解析Parsingn-gram 生成词形变化复数化与单数化与词形还原Word inflection and lemmatization拼写纠正Spelling correction通过扩展机制添加新模型或新语言Add new models or languages through extensionsWordNet 集成WordNet integration其中分类器的四种实现朴素贝叶斯、决策树、正例朴素贝叶斯、最大熵全部位于 src/textblob/classifiers.pyWordNet 集成在 src/textblob/wordnet.py扩展机制的使用说明见 docs/extensions.rst。安装与语料库下载安装命令README 给出的安装与初始化步骤只有两条命令$ pip install -U textblob $ python -m textblob.download_corpora第一条命令从 PyPI 安装或升级textblob 包第二条命令下载 TextBlob 运行所需的 NLTK 语料库。注意第二步不能省略因为 TextBlob 的默认组件分词器、词性标注器、名词短语提取器、词形还原都依赖 NLTK 的离线语料。语料库明细lite 与全量从 src/textblob/download_corpora.py 的源码可以精确看到语料清单最小必需语料MIN_CORPORA对应lite模式brownFastNPExtractor名词短语提取所需punkt_tabWordTokenizer分词所需wordnet词形还原lemmatization所需averaged_perceptron_tagger_engNLTKTagger词性标注所需。附加语料ADDITIONAL_CORPORA全量模式会额外下载conll2000ConllExtractor名词短语提取器所需movie_reviewsNaiveBayesAnalyzer情感分析器训练所需见 src/textblob/en/sentiments.py 的NaiveBayesAnalyzer.train()它用该语料的正/负影评文件训练朴素贝叶斯分类器。如果只打算使用默认模型可以只下载最小集$ python -m textblob.download_corpora lite该命令对应源码中的download_lite()函数不带参数时执行download_all()下载全部六项语料。执行完毕后命令行会打印Finished.。语言数据文件除了 NLTK 语料TextBlob 还随包内置了一批 pattern 风格的语言数据文件位于 src/textblob/en 目录下由 src/textblob/en/init.py 在导入时加载文件用途en-lexicon.txt情感词词典极性/主观性分值en-morphology.txt词形变化规则en-context.txt情感上下文消歧规则en-entities.txt实体词表en-sentiment.xml情感分析器配置文件en-spelling.txt拼写纠正词频表例如Spelling对象读取en-spelling.txtsrc/textblob/en/init.py 第 15 行Sentiment对象加载en-sentiment.xml并指定否定词(no, not, nt, never)与修饰词(RB,)第 74-82 行。快速上手从一段文本到结构化的语言洞察README 给出了一个完整的示例——对一段影评文本进行词性标注、名词短语提取与逐句情感打分from textblob import TextBlob text The titular threat of The Blob has always struck me as the ultimate movie monster: an insatiably hungry, amoeba-like mass able to penetrate virtually any safeguard, capable of--as a doomed doctor chillingly describes it--assimilating flesh on contact. Snide comparisons to gelatin be damned, its a concept with the most devastating of potential consequences, not unlike the grey goo scenario proposed by technological theorists fearful of artificial intelligence run rampant. blob TextBlob(text) blob.tags # [(The, DT), (titular, JJ), # (threat, NN), (of, IN), ...] blob.noun_phrases # WordList([titular threat, blob, # ultimate movie monster, # amoeba-like mass, ...]) for sentence in blob.sentences: print(sentence.sentiment.polarity) # 0.060 # -0.341下面逐项拆解这个示例背后的 API 与实现。创建 TextBlob 对象导入并构造一个TextBlob from textblob import TextBlob wiki TextBlob(Python is a high-level, general-purpose programming language.)构造函数的参数定义见 src/textblob/blob.py第一个参数text必须是字符串非字符串会抛出TypeError其余均为可选的可插拔模型组件tokenizer、pos_tagger、np_extractor、analyzer、parser、classifier传None时使用类默认值。词性标注POS Tagging通过blob.tags等价于blob.pos_tags获得(单词, 词性标签)列表 wiki.tags [(Python, NNP), (is, VBZ), (a, DT), (high-level, JJ), (general-purpose, JJ), (programming, NN), (language, NN)]标签采用 Penn Treebank 词性标记集如NNP专有名词、VBZ第三人称单数动词、DT限定词、JJ形容词、NN名词。实现上pos_tags属性把每个句子委托给默认的NLTKTaggersrc/textblob/blob.py并过滤掉纯标点标签。名词短语提取Noun Phrase Extraction wiki.noun_phrases WordList([python])noun_phrases属性调用默认的FastNPExtractor基于 brown 语料训练并将结果统一转为小写、过滤掉长度 ≤ 1 的短语src/textblob/blob.py。默认返回类型是WordList。情感分析Sentiment Analysissentiment属性返回一个命名元组Sentiment(polarity, subjectivity)src/textblob/blob.py testimonial TextBlob(Textblob is amazingly simple to use. What great fun!) testimonial.sentiment Sentiment(polarity0.39166666666666666, subjectivity0.4357142857142857) testimonial.sentiment.polarity 0.39166666666666666极性polarity[-1.0, 1.0]区间的浮点数负值偏消极、正值偏积极主观性subjectivity[0.0, 1.0]区间的浮点数0.0 表示非常客观1.0 表示非常主观。这两个取值范围在 quickstart 文档与源码 docstring 中均有明确声明。默认分析器是PatternAnalyzersrc/textblob/en/sentiments.py它封装 pattern 的英文情感算法如果调用blob.sentiment_assessments还会额外返回每个被评估 token 的极性/主观性明细assessments。另外TextBlob 还提供blob.polarity与blob.subjectivity两个便捷属性分别只取对应分量src/textblob/blob.py。分词切出单词与句子 zen TextBlob( ... Beautiful is better than ugly. ... Explicit is better than implicit. ... Simple is better than complex. ... ) zen.words WordList([Beautiful, is, better, than, ugly, Explicit, is, better, than, implicit, Simple, is, better, than, complex]) zen.sentences [Sentence(Beautiful is better than ugly.), Sentence(Explicit is better than implicit.), Sentence(Simple is better than complex.)]blob.words词 token 列表默认剔除标点类型为WordListblob.sentencesSentence对象列表Sentence拥有与TextBlob相同的属性与方法如sentimentblob.tokens包含标点在内的完整 token 列表src/textblob/blob.py。分词底层是 NLTK 的WordTokenizer词级与SentenceTokenizer句级基于 Punkt 无监督算法详见 src/textblob/tokenizers.py。Sentence对象还带有start与end属性可以定位它在整个TextBlob中的字符起止下标src/textblob/blob.py。词形变化与词形还原TextBlob.words/Sentence.words中的每个元素都是Word对象str的子类src/textblob/blob.py内置丰富的词形方法 sentence TextBlob(Use 4 spaces per indentation level.) sentence.words WordList([Use, 4, spaces, per, indentation, level]) sentence.words[2].singularize() space sentence.words[-1].pluralize() levels词形还原lemmatization基于 WordNet 的 morphy 机制 from textblob import Word w Word(octopi) w.lemmatize() octopus w Word(went) w.lemmatize(v) # 传入 WordNet 词性动词 go源码中lemmatize()会把 Penn 词性标签转换为 WordNet 标签_penn_to_wordnet函数再调用nltk.stem.WordNetLemmatizersrc/textblob/blob.py。Word还提供了stem()方法支持 Porter、Lancaster、Snowball 三种 NLTK 词干提取器默认 Porter。拼写纠正TextBlob 与Word都支持拼写纠正 b TextBlob(I havv goood speling!) print(b.correct()) I have good spelling! from textblob import Word w Word(falibility) w.spellcheck() [(fallibility, 1.0)]TextBlob.correct()整体纠正文本拼写src/textblob/blob.pyWord.spellcheck()返回(候选词, 置信度)元组列表src/textblob/blob.py。该功能基于 Peter Norvig 的 How to Write a Spelling Corrector 方法在 pattern 库中的实现quickstart 文档脚注说明了这一点官方文档给出的准确率约为 70%。词与名词短语频率统计两种统计途径 monty TextBlob(We are no longer the Knights who say Ni. ... We are now the Knights who say Ekki ekki ekki PTANG.) monty.word_counts[ekki] # 方式一word_counts 字典不区分大小写 3 monty.words.count(ekki) # 方式二count() 方法 3 monty.words.count(ekki, case_sensitiveTrue) # 可指定大小写敏感 2word_counts返回普通字典搜索不区分大小写未出现的词频率为 0src/textblob/blob.pyWordList.count()的case_sensitive参数默认Falsesrc/textblob/blob.py名词短语同理可用wiki.noun_phrases.count(python)另有np_counts字典可用。句法解析Parsing b TextBlob(And now for something completely different.) print(b.parse()) And/CC/O/O now/RB/B-ADVP/O for/IN/B-PP/B-PNP something/NN/B-NP/I-PNP completely/RB/B-ADJP/O different/JJ/I-ADJP/O ././O/Oparse()默认使用 pattern 的解析器PatternParsersrc/textblob/blob.py输出格式为词/词性/组块标签/介词短语标签其中B-/I-前缀表示组块边界begin/insideO表示组块外。n-grams blob TextBlob(Now is better than never.) blob.ngrams(n3) [WordList([Now, is, better]), WordList([is, better, than]), WordList([better, than, never])]ngrams(n)返回连续 n 个词的滑动窗口列表默认n3n 0时返回空列表src/textblob/blob.py。TextBlob 就是 Python 字符串TextBlob 刻意实现了一整套字符串语义StringlikeMixin/BlobComparableMixin见 src/textblob/blob.py zen[0:19] # 子串切片 TextBlob(Beautiful is better) zen.upper() # 字符串方法 TextBlob(BEAUTIFUL IS BETTER THAN UGLY. ...) zen.find(Simple) # 查找 65 apple_blob banana_blob # 比较 True apple_blob apples True apple_blob and banana_blob # 拼接 TextBlob(apples and bananas) {0} and {1}.format(apple_blob, banana_blob) apples and bananas切片、upper()、find()、比较、拼接、格式化均返回TextBlob或正常结果使得文本处理代码与纯字符串操作无缝衔接。WordNet 集成Word对象可访问 WordNet 同义词集synset与释义 from textblob import Word from textblob.wordnet import VERB word Word(octopus) word.synsets [Synset(octopus.n.01), Synset(octopus.n.02)] Word(hack).get_synsets(posVERB) [Synset(chop.v.05), Synset(hack.v.02), ...] Word(octopus).definitions [tentacles of octopus prepared as food, bottom-living cephalopod having a soft oval body with eight long tentacles]还可以直接构造Synset并计算语义相似度 from textblob.wordnet import Synset octopus Synset(octopus.n.02) shrimp Synset(shrimp.n.03) octopus.path_similarity(shrimp) 0.1111111111111111底层是 NLTK 的 WordNet 接口src/textblob/blob.py 中_wordnet nltk.corpus.wordnet以惰性加载方式使用。注意Word(went).lemmatize(v)中的v属于 WordNet 词性标记与 Penn 标签如VB不同二者会在lemmatize()内部自动换算。底层架构可插拔的组件模型TextBlob 的核心设计是可插拔组件pluggable components。在 src/textblob/blob.py 的BaseBlob中定义了五个类级默认组件np_extractor FastNPExtractor() pos_tagger NLTKTagger() tokenizer WordTokenizer() analyzer PatternAnalyzer() parser PatternParser()每个组件都有对应的抽象基类定义于 src/textblob/base.py构造函数通过_validated_param校验传入实例的类型不合法会抛出ValueErrorsrc/textblob/blob.py。这意味着你可以自由替换分词器WordTokenizer、SentenceTokenizer或任何 NLTK 兼容 tokenizer词性标注器NLTKTagger、PatternTagger见 src/textblob/taggers.py名词短语提取器FastNPExtractor、ConllExtractor见 src/textblob/np_extractors.py情感分析器PatternAnalyzer、NaiveBayesAnalyzer后者输出Sentiment(classification, p_pos, p_neg)基于电影评论语料见 src/textblob/en/sentiments.py解析器PatternParser见 src/textblob/parsers.py。Blobber共享模型的工厂如果需要批量处理大量文本逐个TextBlob(text, ...)传入组件既繁琐又浪费内存。Blobber是一个工厂类它创建的所有TextBlob共享同一套模型实例src/textblob/blob.py from textblob import Blobber from textblob.taggers import NLTKTagger from textblob.tokenizers import SentenceTokenizer tb Blobber(pos_taggerNLTKTagger(), tokenizerSentenceTokenizer()) blob1 tb(This is one blob.) blob2 tb(This blob has the same tagger and tokenizer.) blob1.pos_tagger is blob2.pos_tagger True这在处理大规模语料时能显著减少模型加载开销。文本分类实战TextBlob 内置的文本分类器封装了 NLTK 的nltk.classify模块统一通过 src/textblob/classifiers.py 暴露。朴素贝叶斯分类器NaiveBayesClassifier训练数据是(文本, 标签)元组列表训练后即可分类 from textblob import TextBlob from textblob.classifiers import NaiveBayesClassifier train [ ... (I love this sandwich., pos), ... (This is an amazing place!, pos), ... (I feel very good about these beers., pos), ... (I do not like this restaurant, neg), ... (I am tired of this stuff., neg), ... (I cant deal with this, neg), ... (My boss is horrible., neg) ... ] cl NaiveBayesClassifier(train) cl.classify(I feel amazing!) pos blob TextBlob(The beer is good. But the hangover is horrible., classifiercl) for s in blob.sentences: ... print(s) ... print(s.classify()) ... The beer is good. pos But the hangover is horrible. neg关键点把训练好的分类器通过classifiercl传入TextBlobSentence.classify()即可对每个句子独立分类BaseBlob.classify()在未设置分类器时会抛出NameErrorsrc/textblob/blob.pyNaiveBayesClassifier还提供prob_classify(text)返回标签概率分布、accuracy(test_set)计算测试集准确率、update(new_data)增量训练src/textblob/classifiers.py训练集也支持文件输入CSV/JSON 等格式自动检测逻辑在_read_data与 src/textblob/formats.py仓库中提供了样例数据 tests/data.csv、tests/data.json、tests/data.tsv。其他分类器同一抽象基类NLTKClassifier之下还有src/textblob/classifiers.pyDecisionTreeClassifier决策树分类器支持pretty_format()/pprint()与pseudocode()输出树结构与伪代码PositiveNaiveBayesClassifier适用于只有正例标注、其余未标注的半监督二分类场景构造参数为positive_set与unlabeled_set可调positive_prob_priorMaxEntClassifier最大熵分类器支持prob_classify()概率输出。分类器在 tests/test_classifiers.py 中有完整测试覆盖可当作使用范例阅读。扩展机制新语言与新模型TextBlob 支持通过扩展extensions挂载自定义模型与新语言官方说明见 docs/extensions.rst安装方式为$ pip install textblob-name其中name为扩展包名。文档列出的可用扩展包括语言扩展textblob-fr法语、textblob-de德语词性标注器textblob-aptagger基于平均感知机 Averaged Perceptron 的快速标注器。如需自行开发扩展可参考仓库内的 CONTRIBUTING.rst 与贡献指南中的扩展开发章节。文档资源与许可快速入门教程docs/quickstart.rst覆盖本文大部分 API 的完整交互式示例进阶用法docs/advanced_usage.rst涵盖自定义分词器、标注器、组块提取器与分类器流水线API 参考docs/api_reference.rst全部公开类的签名与文档变更日志docs/changelog.rst 与根目录 CHANGELOG.rst记录了各版本 API 演进例如 0.8.0 起类改由textblob顶层导入项目主页文档入口docs/index.rst。许可方面README 声明 TextBlob 采用MIT 协议详见仓库内 LICENSE同时由于部分代码源自 pattern 库仓库附有 NOTICE 文件说明归属与许可信息src/textblob/en/init.py 首行注释也做了对应声明。小结围绕 README.rst 提供的骨架本文结合源码完整梳理了 TextBlob 的实战路径pip install -U textblobpython -m textblob.download_corpora完成环境就绪TextBlob(text)一行构造对象后即可用.tags、.noun_phrases、.sentiment、.words、.sentences、.ngrams()、.parse()等属性与方法完成从词级到句级的语言洞察Word/WordList提供词形变化、词形还原、拼写纠正与 WordNet 集成Blobber与可插拔组件模型让大规模批处理与自定义 NLP 流水线成为可能classifiers模块让基于朴素贝叶斯、决策树等算法的文本分类开箱即用。无论你是做舆情分析、评论情感标注、文本清洗还是机器学习特征工程这套 API 都能显著降低 NLP 的入门与工程化成本。赞分享NLP人工智能【免费下载链接】TextBlobSimple, Pythonic, text processing--Sentiment analysis, part-of-speech tagging, noun phrase extraction, translation, and more.项目地址https://gitcode.com/gh_mirrors/te/TextBlob点击查看免费下载相关推荐PaddleNLP Taskflow 知识挖掘knowledge_mining实战WordTag 词类标注与 NPTag 名词短语标注PaddleNLP Taskflow 知识挖掘knowledge_mining实战WordTag 词类标注与 NPTag 名词短语标注 PaddleNLP人工智能大模型预训练微调LoRARLHF强化学习分布式训练模型推理服务推理引擎模型量化模型压缩本地部署NLPJSON API Serializer最佳实践生产环境部署的注意事项JSON API Serializer最佳实践生产环境部署的注意事项 JSON API Serializer是一款Node.js框架无关的反序列化库能够PaddleHub LAC 中文词法分析模块实战指南分词、词性标注与专名识别全解析PaddleHub LAC 中文词法分析模块实战指南分词、词性标注与专名识别全解析 本指南围绕 PaddleFormers 仓库中的 PaddleHub LA人工智能大模型微调模型推理服务创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
