前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >文本处理工具 - TextBlob

文本处理工具 - TextBlob

作者头像
种花家的奋斗兔
发布于 2020-11-12 15:57:16
发布于 2020-11-12 15:57:16
3.1K00
代码可运行
举报
运行总次数:0
代码可运行

TextBlob基本介绍

TextBlob是一个用Python编写的开源的文本处理库。它可以用来执行很多自然语言处理的任务,比如,词性标注,名词性成分提取,情感分析,文本翻译,等等。你可以在官方文档阅读TextBlog的所有特性。

基本功能

  • Noun phrase extraction 短语提取
  • Part-of-speech tagging 词汇标注
  • Sentiment analysis 情感分析
  • Classification (Naive Bayes, Decision Tree) 分类
  • Language translation and detection powered by Google Translate 语言翻译和检查(谷歌翻译支持)
  • Tokenization (splitting text into words and sentences) 分词、分句
  • Word and phrase frequencies 词、短语频率
  • Parsing 语法分析
  • n-grams N元标注
  • Word inflection (pluralization and singularization) and lemmatization 词反射及词干提取
  • Spelling correction 拼写准确性
  • Add new models or languages through extensions 添加新模型或语言通过表达
  • WordNet integration WordNet整合

快速开始:

Create a TextBlob(创建一个textblob对象)

First, the import. TextBlob 类

>>> from textblob import TextBlob

Let’s create our first TextBlob.

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
>>> wiki = TextBlob("Python is a high-level, general-purpose programming language.")

Part-of-speech Tagging(词性标注)

Part-of-speech tags can be accessed through the tags property.

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
>>> wiki.tags
[('Python', 'NNP'), ('is', 'VBZ'), ('a', 'DT'), ('high-level', 'JJ'), ('general-purpose', 'JJ'), ('programming', 'NN'), ('language', 'NN')]

Noun Phrase Extraction(名词短语列表)

Similarly, noun phrases are accessed through the noun_phrases property. 注意:只提取名词短语

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
>>> wiki.noun_phrases
WordList(['python'])

Sentiment Analysis(情感分析)

返回一个元组 Sentiment(polarity, subjectivity).

The polarity score is a float within the range [-1.0, 1.0]. -1.0 消极,1.0积极

The subjectivity is a float within the range [0.0, 1.0] 0.0 表示客观,1.0表示主观.

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
>>> testimonial = TextBlob("Textblob is amazingly simple to use. What great fun!")
>>> testimonial.sentiment
Sentiment(polarity=0.39166666666666666, subjectivity=0.4357142857142857)
>>> testimonial.sentiment.polarity
0.39166666666666666

Tokenization(分词和分句)

You can break TextBlobs into words or sentences.

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
>>> 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.")]

Sentence 对象 和TextBlobs 一样,有相同的方法和属性.

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
>>> for sentence in zen.sentences:
...     print(sentence.sentiment)

Words Inflection and Lemmatization(词反射及词干提取:单复数、过去式等)

Each word in TextBlob.words or Sentence.words is a Word object (a subclass of unicode) with useful methods, e.g. for word inflection.

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
singularize() 变单数, pluralize()变复数,用在对名词进行处理,且会考虑特殊名词单复数形式
代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
>>> 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'

Word 类 :lemmatize() 方法 对单词进行词形还原,名词找单数,动词找原型。所以需要一次处理名词,一次处理动词

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
>>> from textblob import Word
>>> w = Word("octopi")
>>> w.lemmatize()     # 默认只处理名词
'octopus'
>>> w = Word("went")
>>> w.lemmatize("v")  # 对动词原型处理
'go'

WordNet Integration (WordNet整合)

You can access the synsets for a Word via the synsets 属性 或者用 get_synsets 方法只查看部分或全部synset.

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
>>> 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(pos=VERB)    # 只查找 该词作为 动词 的集合,参数为空时和synsets方法相同
[Synset('chop.v.05'), Synset('hack.v.02'), Synset('hack.v.03'), Synset('hack.v.04'), Synset('hack.v.05'), Synset('hack.v.06'), Synset('hack.v.07'), Synset('hack.v.08')]

You can access the definitions for each synset via the definitions property or the define()method, which can also take an optional part-of-speech argument.

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
>>> Word("octopus").definitions  #单词“章鱼”的定义
['tentacles of octopus prepared as food', 'bottom-living cephalopod having a soft oval body with eight long tentacles']    # '章鱼的触手是食物','底硒头足类动物,身体软而呈卵形,有八只长触须'

You can also create synsets directly.

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
>>> from textblob.wordnet import Synset
>>> octopus = Synset('octopus.n.02')
>>> shrimp = Synset('shrimp.n.03')
>>> octopus.path_similarity(shrimp)
0.1111111111111111

For more information on the WordNet API, see the NLTK documentation on the Wordnet Interface.

WordLists

A WordList is just a Python list with additional methods. 属性words : 一个包含句子分词的list

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
>>> animals = TextBlob("cat dog octopus")
>>> animals.words
WordList(['cat', 'dog', 'octopus'])
>>> animals.words.pluralize()
WordList(['cats', 'dogs', 'octopodes'])

Spelling Correction(拼写校正)

Use the correct() method to attempt spelling correction.

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
>>> b = TextBlob("I havv goood speling!")
>>> print(b.correct())
I have good spelling!

Word objects have a spellcheck() Word.spellcheck() method that returns a list of (word,confidence) tuples with spelling suggestions.

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
>>> from textblob import Word
>>> w = Word('falibility')
>>> w.spellcheck()
[('fallibility', 1.0)]

Spelling correction is based on Peter Norvig’s “How to Write a Spelling Corrector”[1] as implemented in the pattern library. It is about 70% accurate [2].

Get Word and Noun Phrase Frequencies(单词词频)

There are two ways to get the frequency of a word or noun phrase in a TextBlob. 两种方法来获取单词频次

The first is through the word_counts dictionary. 从属性word_counts 字典获取

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
>>> 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']
3

If you access the frequencies this way, the search will not be case sensitive, and words that are not found will have a frequency of 0.

The second way is to use the count() method. 用count ()方法获取

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
>>> monty.words.count('ekki')                  #单词频次
3

You can specify whether or not the search should be case-sensitive (default is False).

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
>>> monty.words.count('ekki', case_sensitive=True)   #设置大小写敏感,默认不区分
2

Each of these methods can also be used with noun phrases.

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
>>> wiki.noun_phrases.count('python')   #短语频次
1

Translation and Language Detection(翻译及语言检测语言)

New in version 0.5.0.

TextBlobs can be translated between languages.

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
>>> en_blob = TextBlob(u'Simple is better than complex.')
>>> en_blob.translate(to='es')
TextBlob("Simple es mejor que complejo.")

If no source language is specified, TextBlob will attempt to detect the language. You can specify the source language explicitly, like so. Raises TranslatorError if the TextBlob cannot be translated into the requested language or NotTranslated if the translated result is the same as the input string.

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
>>> chinese_blob = TextBlob(u"美丽优于丑陋")
>>> chinese_blob.translate(from_lang="zh-CN", to='en')
TextBlob("Beautiful is better than ugly")

You can also attempt to detect a TextBlob’s language using TextBlob.detect_language().

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
>>> b = TextBlob(u"بسيط هو أفضل من مجمع")
>>> b.detect_language()
'ar'

As a reference, language codes can be found here.

Language translation and detection is powered by the Google Translate API.

Parsing(解析)

Use the parse() method to parse the text. 句法解析 parse() 方法

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
>>> 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/O

By default, TextBlob uses pattern’s parser [3].

TextBlobs Are Like Python Strings!(TextBlobs像是字符串)

You can use Python’s substring syntax.

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
>>> zen[0:19]
TextBlob("Beautiful is better")

You can use common string methods.

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
>>> zen.upper()
TextBlob("BEAUTIFUL IS BETTER THAN UGLY. EXPLICIT IS BETTER THAN IMPLICIT. SIMPLE IS BETTER THAN COMPLEX.")
>>> zen.find("Simple")
65

You can make comparisons between TextBlobs and strings.

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
>>> apple_blob = TextBlob('apples')
>>> banana_blob = TextBlob('bananas')
>>> apple_blob < banana_blob
True
>>> apple_blob == 'apples'
True

You can concatenate and interpolate TextBlobs and strings.

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
>>> apple_blob + ' and ' + banana_blob
TextBlob("apples and bananas")
>>> "{0} and {1}".format(apple_blob, banana_blob)
'apples and bananas'

n-grams(提取前n个字)

The TextBlob.ngrams() method returns a list of tuples of n successive words.

ngrams(n) 方法返回 句子每 n 个连续单词为一个元素的 list

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
>>> blob = TextBlob("Now is better than never.")
>>> blob.ngrams(n=3)
[WordList(['Now', 'is', 'better']), WordList(['is', 'better', 'than']), WordList(['better', 'than', 'never'])]

Get Start and End Indices of Sentences(句子开始和结束的索引)

Use sentence.start and sentence.end to get the indices where a sentence starts and ends within a TextBlob.

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
>>> for s in zen.sentences:
...     print(s)
...     print("---- Starts at index {}, Ends at index {}".format(s.start, s.end))
Beautiful is better than ugly.
---- Starts at index 0, Ends at index 30
Explicit is better than implicit.
---- Starts at index 31, Ends at index 64
Simple is better than complex.
---- Starts at index 65, Ends at index 95

文档

TextBlob is a Python library for processing textual data. It provides a simple API for diving into common (NLP) tasks such as part-of-speech tagging, noun phrase extraction, sentiment analysis, classification, translation, and more.

[html] view plain copy

  1. from textblob import TextBlob
  2. text = '''
  3. The titular threat of The Blob has always struck me as the ultimate movie
  4. monster: an insatiably hungry, amoeba-like mass able to penetrate
  5. virtually any safeguard, capable of--as a doomed doctor chillingly
  6. describes it--"assimilating flesh on contact.
  7. Snide comparisons to gelatin be damned, it's a concept with the most
  8. devastating of potential consequences, not unlike the grey goo scenario
  9. proposed by technological theorists fearful of
  10. artificial intelligence run rampant.
  11. '''
  12. blob = TextBlob(text)
  13. blob.tags # [('The', 'DT'), ('titular', 'JJ'),
  14. # ('threat', 'NN'), ('of', 'IN'), ...]
  15. blob.noun_phrases # WordList(['titular threat', 'blob',
  16. # 'ultimate movie monster',
  17. # 'amoeba-like mass', ...])
  18. for sentence in blob.sentences:
  19. print(sentence.sentiment.polarity)
  20. # 0.060
  21. # -0.341
  22. blob.translate(to="es") # 'La amenaza titular de The Blob...

TextBlob stands on the giant shoulders of NLTK and pattern, and plays nicely with both.

Features

  • Noun phrase extraction
  • Part-of-speech tagging
  • Sentiment analysis
  • Classification (Naive Bayes, Decision Tree)
  • Language translation and detection powered by Google Translate
  • Tokenization (splitting text into words and sentences)
  • Word and phrase frequencies
  • Parsing
  • n-grams
  • Word inflection (pluralization and singularization) and lemmatization
  • Spelling correction
  • Add new models or languages through extensions
  • WordNet integration
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2018/02/05 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
暂无评论
推荐阅读
编辑精选文章
换一批
初学者|手把手带你学TextBlob
本文介绍了TextBlob的使用方法,这是一个用Python编写的开源的文本处理库。它可以用来执行很多自然语言处理的任务,比如,词性标注,名词性成分提取,情感分析,文本翻译,等等。
yuquanle
2019/10/08
2.7K0
【python】教你彻底了解Python中的自然语言处理(NLP)
​​​自然语言处理(Natural Language Processing,简称NLP)是人工智能的一个重要分支,旨在通过计算机理解和生成人类语言。在Python中,有许多强大的库和工具可以用于自然语言处理。本文将深入探讨Python在自然语言处理中的应用,涵盖自然语言处理的基本概念、常用的NLP库、文本预处理、词嵌入与特征提取、文本分类、情感分析、命名实体识别,以及一些实际应用示例。
E绵绵
2025/05/25
1440
Python相关机器学习‘武器库’
开始学习Python,之后渐渐成为我学习工作中的第一辅助脚本语言,虽然开发语言是Java,但平时的很多文本数据处理任务都交给了Python。这些年来,接触和使用了很多Python工具包,特别是在文本处理,科学计算,机器学习和数据挖掘领域,有很多很多优秀的Python工具包可供使用,所以作为Pythoner,也是相当幸福的。如果仔细留意微博和论坛,你会发现很多这方面的分享,自己也Google了一下,发现也有同学总结了“Python机器学习库”,不过总感觉缺少点什么。最近流行一个词,全栈工程师(full st
智能算法
2018/04/02
1K0
Python文本处理2个小案例(文本嗅探与关键词占比统计)
问题描述:有一些句子和一些关键词,现在想找出包含至少一个关键词的那些句子(文本嗅探),可以参考print('='*30)之前的代码。如果想进一步计算每个句子中的关键词占比(句子中所有关键词长度之和/句子长度),可以参考后面的代码。关键词占比是比较常用的一个文本分类标准,如果想根据关键词占比对句子进行分类的话,可以自行补充代码。 本文主要演示列表推导式、字符串对象用法以及生成器表达式和内置函数的用法。 from random import choice from string import ascii_let
Python小屋屋主
2018/04/16
1.4K0
TextBlob,一个超好用的Python文本分析库!
TextBlob是一个非常有趣且对于很多Python开发者来说可能还不那么熟悉的库。它提供了一个简单的API,用于处理文本数据,进行自然语言处理(NLP)任务,比如情感分析、词性标注、翻译等。TextBlob基于NLTK和Pattern库,结合了它们的强大功能,同时提供了更友好和更简单的接口。
double
2024/02/26
8850
TextBlob,一个超好用的Python文本分析库!
05 奇妙的Python库之【textblob(文本处理)】
TextBlob 是一款 Pythonic 的文本处理工具,用于处理文本数据,它提供了一个简单的 API,用于潜入常见的自然语言处理(NLP)任务,如词性标注、名词短语提取、情感分析、分类等
测试开发囤货
2021/09/08
2.5K0
整理了25个Python文本处理案例,收藏!
Python 处理文本是一项非常常见的功能,本文整理了多种文本提取及NLP相关的案例,还是非常用心的
周萝卜
2022/02/10
2K0
文本数据处理的终极指南-[NLP入门]
简介 实现任何程度或者级别的人工智能所必需的最大突破之一就是拥有可以处理文本数据的机器。值得庆幸的是,全世界文本数据的数量在最近几年已经实现指数级增长。这也迫切需要人们从文本数据中挖掘新知识、新观点。
用户1332428
2018/03/30
1.4K0
文本数据处理的终极指南-[NLP入门]
【Python环境】Python 网页爬虫 &文本处理 & 科学计算 &机器学习 &数据挖掘兵器谱
曾经因为NLTK的缘故开始学习Python,之后渐渐成为我工作中的第一辅助脚本语言,虽然开发语言是C/C++,但平时的很多文本数据处理任务都交给了Python。离开腾讯创业后,第一个作品课程图谱也是选择了Python系的Flask框架,渐渐的将自己的绝大部分工作交给了Python。这些年来,接触和使用了很多Python工具包,特别是在文本处理,科学计算,机器学习和数据挖掘领域,有很多很多优秀的Python工具包可供使用,所以作为Pythoner,也是相当幸福的。其实如果仔细留意微博,你会发现很多这方面的分享
陆勤_数据人网
2018/02/26
8900
这篇文献总结了常见的中式英语写法,来看看有没有中枪?
The Most Common Habits from more than 200 English Papers written by Graduate Chinese Engineering Students
生信宝典
2022/01/19
7760
这篇文献总结了常见的中式英语写法,来看看有没有中枪?
【黄啊码】上百个AI提示词模板,不用多想,直接收藏【二】
作为一名中文写作改进助理,你的任务是改进所提供文本的拼写、语法、清晰、简洁和整体可读性,同时分解长句,减少重复,并提供改进建议。请只提供文本的更正版本,避免包括解释。请从编辑以下文本开始:[文章内容]
黄啊码
2024/07/23
2100
【黄啊码】上百个AI提示词模板,不用多想,直接收藏【二】
【NLP】竞赛必备的NLP库
本周我们给大家整理了机器学习和竞赛相关的NLP库,方便大家进行使用,建议收藏本文。
黄博的机器学习圈子
2020/09/29
1.9K0
【NLP】竞赛必备的NLP库
独家 | 快速掌握spacy在python中进行自然语言处理(附代码&链接)
本文简要介绍了如何使用spaCy和Python中的相关库进行自然语言处理(有时称为“文本分析”)。以及一些目前最新的相关应用。
数据派THU
2019/10/29
3.5K0
独家 | 快速掌握spacy在python中进行自然语言处理(附代码&链接)
【论文推荐】最新5篇情感分析相关论文—深度学习情感分析综述、情感分析语料库、情感预测性、上下文和位置感知的因子分解模型、LSTM
【导读】专知内容组整理了最近五篇情感分析(Sentiment Analysis)相关文章,为大家进行介绍,欢迎查看! 1. Deep Learning for Sentiment Analysis : A Survey(深度学习情感分析综述) ---- ---- 作者:Lei Zhang,Shuai Wang,Bing Liu 摘要:Deep learning has emerged as a powerful machine learning technique that learns multiple
WZEARW
2018/04/13
2K0
【论文推荐】最新5篇情感分析相关论文—深度学习情感分析综述、情感分析语料库、情感预测性、上下文和位置感知的因子分解模型、LSTM
polyglot:Pipeline 多语言NLP工具
目前,在NLP任务处理中,Python支持英文处理的开源包有NLTK、Scapy、StanfordCoreNLP、GATE、OPenNLP,支持中文处理的开源工具包有Jieba、ICTCLAS、THU LAC、HIT LTP,但是这些工具大部分仅对特定类型的语言提供支持。本文将介绍功能强大的支持Pipeline方式的多语言处理Python工具包:polyglot。该项目最早是由AboSamoor在2015年3月16日在GitHub上开源的项目,已经在Github收集star 1021个。
AINLP
2019/10/10
3.2K0
polyglot:Pipeline 多语言NLP工具
python人工智能学习笔记_[Python] 人工智能与自然语言处理学习笔记(1)[通俗易懂]
最近我参加了一个人工智能与自然语言处理的课程,这是第一周的学习笔记。这份笔记不涉及一般知识,全部都是与实践(我在这门课上的作业)有关的总结。
全栈程序员站长
2022/08/31
3180
NLP 中的通用数据增强方法及针对 NER 的变种
本文结合 A Visual Survey of Data Augmentation in NLP 和最新的综述论文 A Survey of Data Augmentation Approaches for NLP,大致总结了目前 NLP 领域的通用数据增强方法和几种针对如 NER 的序列标注模型进行适配的变种方法,关于后者,重点介绍了基于 mixup 改进的 SeqMix 方法。
Alan Lee
2021/12/07
1.6K0
NLP 中的通用数据增强方法及针对 NER 的变种
NLP最强工具包NLTK入门教程
在当今信息爆炸的时代,自然语言处理(Natural Language Processing, NLP)已成为人工智能领域的重要研究方向之一。无论是机器翻译、情感分析、文本分类,还是语音识别,NLP技术都在其中扮演着关键角色。
皮大大
2025/05/09
3480
Sentiment Analysis情感分析——珍藏版
本文为Stanford Dan Jurafsky & Chris Manning: Natural Language Processing 课程笔记。
zenRRan
2018/07/25
2K0
Sentiment Analysis情感分析——珍藏版
Natural Language Processing
Natural Language Processing (NLP) is one of the hottest areas of artificial intelligence (AI) thanks to applications like text generators that compose coherent essays, chatbots that fool people into thinking they’re sentient, and text-to-image programs that produce photorealistic images of anything you can describe. Recent years have brought a revolution in the ability of computers to understand human languages, programming languages, and even biological and chemical sequences, such as DNA and protein structures, that resemble language. The latest AI models are unlocking these areas to analyze the meanings of input text and generate meaningful, expressive output.
用户6026865
2023/03/03
3690
Natural Language Processing
推荐阅读
相关推荐
初学者|手把手带你学TextBlob
更多 >
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
本文部分代码块支持一键运行,欢迎体验
本文部分代码块支持一键运行,欢迎体验