自然语言处理秘籍-一-

173 阅读38分钟

自然语言处理秘籍(一)

原文:Natural Language Processing Recipes

协议:CC BY-NC-SA 4.0

一、提取数据

本章涵盖了文本数据的各种来源以及提取文本数据的方法。文本数据可以为企业提供信息或见解。涵盖以下食谱。

  • 食谱 1。使用 API 收集文本数据

  • 食谱 2。用 Python 读取 PDF 文件

  • 食谱三。阅读 Word 文档

  • 食谱 4。读取 JSON 对象

  • 食谱 5。读取 HTML 页面和 HTML 解析

  • 食谱 6。正则表达式

  • 食谱 7。字符串处理

  • 食谱 8。网页抓取

介绍

在进入这本书的细节之前,让我们看看普遍可用的数据来源。我们需要确定能够帮助解决数据科学用例的潜在数据源。

客户数据

对于任何问题陈述,来源之一是已经存在的数据。企业决定要将数据存储在哪里。数据存储取决于业务类型、数据量以及与数据源相关的成本。以下是一些例子。

  • SQL 数据库

  • 分布式文件系统

  • 云存储

  • 平面文件

免费资源

互联网上有大量的免费数据。你只需要简化问题,并开始探索多个免费的数据源。

网页抓取

使用 Python 中的网络抓取包,从网站、博客、论坛和零售网站中提取内容/数据,以便在获得相应来源的许可后进行审查。

还有很多其他来源,如新闻数据和经济数据,可以用来进行分析。

配方 1-1。收集数据

有很多免费的 API,你可以通过它们收集数据,并用它来解决问题。让我们讨论一下 Twitter API。

问题

您希望使用 Twitter APIs 收集文本数据。

解决办法

Twitter 拥有海量数据,其中蕴含着巨大的价值。社交媒体营销人员以此为生。每天都有大量的推文,每条推文都有故事要讲。当所有这些数据被收集和分析时,它给企业提供了关于他们的公司、产品、服务等等的巨大洞察力。

现在让我们看看如何提取数据,然后在接下来的章节中探讨如何利用它。

它是如何工作的

步骤 1-1。登录 Twitter 开发者门户

https://developer.twitter.com 登录 Twitter 开发者门户。

在 Twitter 开发者门户中创建自己的应用,并获得以下密钥。一旦有了这些凭证,就可以开始提取数据了。

  • 消费者密钥:与应用程序(Twitter、脸书等)相关联的密钥。)

  • 消费者秘密:用于向认证服务器(Twitter、脸书等)认证的密码。)

  • 访问令牌:成功认证密钥后给予客户端的密钥

  • 访问令牌密码:访问密钥的密码

步骤 1-2。在 Python 中执行查询

一旦所有的凭证都准备好了,就使用下面的代码来获取数据。

# Install tweepy
!pip install tweepy
# Import the libraries
import numpy as np
import tweepy
import json
import pandas as pd
from tweepy import OAuthHandler
# credentials

consumer_key = "adjbiejfaaoeh"
consumer_secret = "had73haf78af"
access_token = "jnsfby5u4yuawhafjeh"
access_token_secret = "jhdfgay768476r"
# calling API

auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
# Provide the query you want to pull the data. For example, pulling data for the mobile phone ABC
query ="ABC"
# Fetching tweets

Tweets = api.search(query, count = 10,lang='en',exclude='retweets',tweet_mode='extended')

当搜索产品 ABC 时,该查询提取前十条推文。API 提取英语推文,因为给定的语言是'en'。它不包括转发。

配方 1-2。从 pdf 收集数据

您的大部分数据存储在 PDF 文件中。您需要从这些文件中提取文本,并存储它以供进一步分析。

问题

你想阅读 PDF 文件。

解决办法

阅读 PDF 文件最简单的方法是使用 PyPDF2 库。

它是如何工作的

按照本节中的步骤从 PDF 文件中提取数据。

步骤 2-1。安装并导入所有必需的库

这是第一行代码。

!pip install PyPDF2
import PyPDF2
from PyPDF2 import PdfFileReader

Note

您可以从网上下载任何 PDF 文件,并将其放在运行这个 Jupyter 笔记本或 Python 脚本的位置。

第 2-2 步。从 PDF 文件中提取文本

现在我们来摘抄课文。

#Creating a pdf file object
pdf = open("file.pdf","rb")
#creating pdf reader object
pdf_reader = PyPDF2.PdfFileReader(pdf)
#checking number of pages in a pdf file
print(pdf_reader.numPages)
#creating a page object
page = pdf_reader.getPage(0)
#finally extracting text from the page
print(page.extractText())
#closing the pdf file
pdf.close()

请注意,该功能不适用于扫描的 pdf。

配方 1-3。从 Word 文件中收集数据

接下来我们来看另一个用 Python 读取 Word 文件的小菜谱。

问题

你想读 Word 文件。

解决办法

最简单的方法是使用 docx 库。

它是如何工作的

按照本节中的步骤从 Word 文件中提取数据。

步骤 3-1。安装并导入所有必需的库

下面是安装和导入 docx 库的代码。

#Install docx
!pip install docx
#Import library
from docx import Document

Note

您可以从网上下载任何 Word 文件,并将其放在运行 Jupyter 笔记本或 Python 脚本的位置。

第 3-2 步。从 Word 文件中提取文本

现在让我们来读课文。

#Creating a word file object
doc = open("file.docx","rb")
#creating word reader object
document = docx.Document(doc)
#create an empty string and call this document. #This document variable stores each paragraph in the Word document.
#We then create a "for" loop that goes through each paragraph in the Word document and appends the paragraph.
docu=""
for para in document.paragraphs.
       docu += para.text
#to see the output call docu
print(docu)

配方 1-4。从 JSON 收集数据

JSON 是一种开放的标准文件格式,代表 *JavaScript 对象符号。*当数据从服务器发送到网页时经常使用。这个方法解释了如何读取 JSON 文件/对象。

问题

你想读取一个 JSON 文件/对象。

解决办法

最简单的方法是使用请求和 JSON 库。

它是如何工作的

按照本节中的步骤从 JSON 中提取数据。

步骤 4-1。安装并导入所有必需的库

下面是导入库的代码。

import requests
import json

第 4-2 步。从 JSON 文件中提取文本

现在我们来摘抄课文。

#extracting the text from "https://quotes.rest/qod.json"
r = requests.get("https://quotes.rest/qod.json")
res = r.json()
print(json.dumps(res, indent = 4))
#output
{
    "success": {
        "total": 1
    },
    "contents": {
        "quotes": [
            {
                "quote": "Where there is ruin, there is hope for a treasure.",
                "length": "50",
                "author": "Rumi",
                "tags": [
                    "failure",
                    "inspire",
                    "learning-from-failure"
                ],
                "category": "inspire",
                "date": "2018-09-29",
                "permalink": "https://theysaidso.com/quote/dPKsui4sQnQqgMnXHLKtfweF/rumi-where-there-is-ruin-there-is-hope-for-a-treasure",
                "title": "Inspiring Quote of the day",
                "background": "https://theysaidso.com/img/man_on_the_mountain.jpg",
                "id": "dPKsui4sQnQqgMnXHLKtfweF"
            }
        ],
        "copyright": "2017-19 theysaidso.com"
    }

}
#extract contents
q = res['contents']['quotes'][0]
q
#output
{'author': 'Rumi',
 'background': 'https://theysaidso.com/img/man_on_the_mountain.jpg',
 'category': 'inspire',
 'date': '2018-09-29',
 'id': 'dPKsui4sQnQqgMnXHLKtfweF',
 'length': '50',
 'permalink': 'https://theysaidso.com/quote/dPKsui4sQnQqgMnXHLKtfweF/rumi-where-there-is-ruin-there-is-hope-for-a-treasure',
 'quote': 'Where there is ruin, there is hope for a treasure.',
 'tags': ['failure', 'inspire', 'learning-from-failure'],
 'title': 'Inspiring Quote of the day'}
#extract only quote

print(q['quote'], '\n--', q['author'])
#output
It wasn't raining when Noah built the ark....
-- Howard Ruff

配方 1-5。从 HTML 收集数据

HTML 是超文本标记语言的简称。它构建网页并在浏览器中显示它们。有各种 HTML 标签来构建内容。这个食谱着眼于阅读 HTML 页面。

问题

你想读解析/读 HTML 页面。

解决办法

最简单的方法是使用 bs4 库。

它是如何工作的

按照本节中的步骤从 web 中提取数据。

步骤 5-1。安装并导入所有必需的库

首先,导入库。

!pip install bs4
import urllib.request as urllib2
from bs4 import BeautifulSoup

第 5-2 步。获取 HTML 文件

你可以选择任何你想提取的网站。让我们在这个例子中使用维基百科。

response = urllib2.urlopen('https://en.wikipedia.org/wiki/Natural_language_processing')
html_doc = response.read()

第 5-3 步。解析 HTML 文件

现在我们来获取数据。

#Parsing
soup = BeautifulSoup(html_doc, 'html.parser')
# Formating the parsed html file
strhtm = soup.prettify()
# Print few lines
print (strhtm[:1000])
#output
<!DOCTYPE html>
<html class="client-nojs" dir="ltr" lang="en">
 <head>
  <meta charset="utf-8"/>
  <title>
   Natural language processing - Wikipedia
  </title>
  <script>
   document.documentElement.className = document.documentElement.className.replace( /(^|\s)client-nojs(\s|$)/, "$1client-js$2" );
  </script>
  <script>

   (window.RLQ=window.RLQ||[]).push(function(){mw.config.set({"wgCanonicalNamespace":"","wgCanonicalSpecialPageName":false,"wgNamespaceNumber":0,"wgPageName":"Natural_language_processing","wgTitle":"Natural language processing","wgCurRevisionId":860741853,"wgRevisionId":860741853,"wgArticleId":21652,"wgIsArticle":true,"wgIsRedirect":false,"wgAction":"view","wgUserName":null,"wgUserGroups":["*"],"wgCategories":["Webarchive template wayback links","All accuracy disputes","Articles with disputed statements from June 2018","Wikipedia articles with NDL identifiers","Natural language processing","Computational linguistics","Speech recognition","Computational fields of stud

第 5-4 步。提取标签值

您可以使用以下代码从标记的第一个实例中提取标记的值。

print(soup.title)
print(soup.title.string)
print(soup.a.string)
print(soup.b.string)
#output
 <title>Natural language processing - Wikipedia</title>
Natural language processing - Wikipedia
None
Natural language processing

第 5-5 步。提取特定标签的所有实例

这里我们得到了我们感兴趣的标签的所有实例。

for x in soup.find_all('a'): print(x.string)
#sample output
 None
Jump to navigation
Jump to search
Language processing in the brain
None
None
automated online assistant
customer service
[1]
computer science
artificial intelligence
natural language
speech recognition
natural language understanding
natural language generation

第 5-6 步。从特定标签中提取所有文本

最后,我们得到文本。

for x in soup.find_all('p'): print(x.text)
#sample output
Natural language processing (NLP) is an area of computer science and artificial intelligence concerned with the interactions between computers and human (natural) languages, in particular how to program computers to process and analyze large amounts of natural language data.
Challenges in natural language processing frequently involve speech recognition, natural language understanding, and natural language generation.

The history of natural language processing generally started in the 1950s, although work can be found from earlier periods.
In 1950, Alan Turing published an article titled "Intelligence" which proposed what is now called the Turing test as a criterion of intelligence.

注意,p标签提取了页面上的大部分文本。

配方 1-6。使用正则表达式解析文本

这个菜谱讨论了正则表达式在处理文本数据时是如何有用的。当处理来自 web 的包含 HTML 标签、长文本和重复文本的原始数据时,正则表达式是必需的。在开发应用程序的过程中,以及在输出中,您不需要这样的数据。

您可以使用正则表达式进行各种基本和高级的数据清理。

问题

您希望使用正则表达式来解析文本数据。

解决办法

最好的方法是使用 Python 中的re库。

它是如何工作的

让我们看看在我们的任务中使用正则表达式的一些方法。

基本标志是 I,L,M,S,U,x。

  • re.I忽略大小写。

  • re.L找一个当地的家属。

  • re.M在多行中查找模式。

  • re.S查找点匹配。

  • re.U适用于 Unicode 数据。

  • 以更易读的格式编写正则表达式。

下面描述正则表达式的功能。

  • 查找出现一次的字符 a 和 b: [ab]

  • 查找除 a 和 b 以外的字符:[^ab]

  • 求 a 到 z 的字符范围:[a-z]

  • 查找除 a 到 z : [^a-z]以外的字符范围

  • 查找从 A 到 Z 和 A 到 Z 的所有字符:[a-zA-Z]

  • 查找任意单个字符:[]

  • 查找任何空白字符:\s

  • 查找任何非空白字符:\S

  • 查找任意数字:\d

  • 查找任何非数字:\D

  • 查找任何非单词:\W

  • 查找任何单词:\w

  • 查找 a 或 b: (a|b)

  • 的出现次数要么为零,要么为一

    • 匹配零个或不超过一个事件: a? ; ?

    • a 的出现次数为零或更多次: a* ; * matches zero or more than that

    • a 出现一次或多次: a+ ; + matches occurrences one or more than one time

  • 匹配三个同时出现的: a{3 }

  • 匹配三个或更多同时出现的 a: a{3,}

  • 匹配三到六个同时出现的: a{3,6}

  • 字符串的开头:^

  • 字符串结尾:$

  • 匹配单词边界:\b

  • 非单词边界:\B

re.match()re.search()函数查找模式,然后根据应用程序的要求进行处理。

我们来看看re.match()re.search()的区别。

  • re.match()仅在字符串开头检查匹配。因此,如果它在输入字符串的开头找到一个模式,它将返回匹配的模式;否则,它返回一个名词。

  • re.search()检查字符串中任何地方的匹配。它在给定的输入字符串或数据中查找该模式的所有匹配项。

现在让我们看几个使用这些正则表达式的例子。

符号化

记号化就是把一个句子拆分成单词。一种方法是使用re.split

# Import library
import re
#run the split query
re.split('\s+','I like this book.')
['I', 'like', 'this', 'book.']

关于正则表达式的解释,请参考主食谱。

提取电子邮件 id

提取电子邮件 id 最简单的方法是使用re.findall.

  1. 阅读/创建文档或句子。

  2. 执行re.findall功能。

doc = "For more details please mail us at: xyz@abc.com, pqr@mno.com"

addresses = re.findall(r'[\w\.-]+@[\w\.-]+', doc)
for address in addresses.
    print(address)
#Output
xyz@abc.com
pqr@mno.com

替换电子邮件 id

让我们将句子或文档中的电子邮件 id 替换为其他电子邮件 id。最简单的方法是使用re.sub

  1. 阅读/创建文档或句子。

  2. 执行re.sub功能。

    new_email_address = re.sub(r'([\w\.-]+)@([\w\.-]+)', r'pqr@mno.com', doc)
    print(new_email_address)
    #Output
    For more details please mail us at pqr@mno.com
    
    
doc = "For more details please mail us at xyz@abc.com"

关于正则表达式的解释,请参考配方 1-6。

如果您在使用 regex 处理电子邮件时观察到了这两种情况,那么我们已经实现了一个非常基本的实例。我们声明由@分隔的单词有助于捕获电子邮件 id。然而,可能有许多边缘情况;例如,点(.)包含域名并处理数字、+(加号)等,因为它们可以是电子邮件 ID 的一部分。

以下是提取/查找/替换电子邮件 id 的高级正则表达式。

([a-zA-Z0-9+._-]+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9_-]+)

还有更复杂的方法来处理所有的边缘情况(例如,“电子邮件 id”中的“. co.in”)。请试一试。

从电子书中提取数据并执行正则表达式

让我们通过使用您到目前为止所学的技术来解决一个从电子书中提取数据的案例研究。

  1. 从书中摘录内容。

    # Import library
    import re
    import requests
    #url you want to extract
    url = 'https://www.gutenberg.org/files/2638/2638-0.txt'
    #function to extract
    def get_book(url).
     # Sends a http request to get the text from project Gutenberg
     raw = requests.get(url).text
     # Discards the metadata from the beginning of the book
     start = re.search(r"\*\*\* START OF THIS PROJECT GUTENBERG EBOOK .* \*\*\*",raw ).end()
     # Discards the metadata from the end of the book
     stop = re.search(r"II", raw).start()
     # Keeps the relevant text
     text = raw[start:stop]
     return text
    # processing
    
    def preprocess(sentence).
     return re.sub('[^A-Za-z0-9.]+' , ' ', sentence).lower()
    #calling the above function
    book = get_book(url)
    processed_book = preprocess(book)
    print(processed_book)
    # Output
     produced by martin adamson david widger with corrections by andrew sly the idiot by fyodor dostoyevsky translated by eva martin part i i. towards the end of november during a thaw at nine o clock one morning a train on the warsaw and petersburg railway was approaching the latter city at full speed. the morning was so damp and misty that it was only with great difficulty that the day succeeded in breaking and it was impossible to distinguish anything more than a few yards away from the carriage windows. some of the passengers by this particular train were returning from abroad but the third class carriages were the best filled chiefly with insignificant persons of various occupations and degrees
    
    picked up at the different stations nearer town. all of them seemed weary and most of them had sleepy eyes and a shivering expression while their complexions generally appeared to have taken on the colour of the fog outside. when da
    
    
  2. 使用 regex 对此数据执行探索性数据分析。

    # Count number of times "the" is appeared in the book
    len(re.findall(r'the', processed_book))
    #Output
    302
    #Replace "i" with "I"
    processed_book = re.sub(r'\si\s', " I ", processed_book)
    print(processed_book)
    #output
     produced by martin adamson david widger
    
    with corrections by andrew sly the idiot by fyodor dostoyevsky translated by eva martin part I i. towards the end of november during a thaw at nine o clock one morning a train on the warsaw and petersburg railway was approaching the latter city at full speed. the morning was so damp and misty that it was only with great difficulty that the day succeeded in breaking and it was impossible to distinguish anything more than a few yards away from the carriage windows. some of the passengers by this particular train were returning from abroad but the third class carriages were the best filled chiefly with insignificant persons of various occupations and degrees picked up at the different stations nearer town. all of them seemed weary and most of them had sleepy eyes and a shivering expression while their complexions generally appeared to have taken on the colour of the fog outside. when da
    
    #find all occurance of text in the format "abc--xyz"
    re.findall(r'[a-zA-Z0-9]*--[a-zA-Z0-9]*', book)
    #output
     ['ironical--it',
     'malicious--smile',
     'fur--or',
     'astrachan--overcoat',
     'it--the',
     'Italy--was',
     'malady--a',
     'money--and',
     'little--to',
     'No--Mr',
     'is--where',
     'I--I',
    
     'I--',
     '--though',
     'crime--we',
     'or--judge',
     'gaiters--still',
     '--if',
     'through--well',
     'say--through',
     'however--and',
     'Epanchin--oh',
     'too--at',
     'was--and',
     'Andreevitch--that',
     'everyone--that',
     'reduce--or',
     'raise--to',
     'listen--and',
     'history--but',
     'individual--one',
     'yes--I',
     'but--',
    
     't--not',
     'me--then',
     'perhaps--',
     'Yes--those',
     'me--is',
     'servility--if',
     'Rogojin--hereditary',
     'citizen--who',
     'least--goodness',
     'memory--but',
     'latter--since',
     'Rogojin--hung',
     'him--I',
     'anything--she',
     'old--and',
    
     'you--scarecrow',
     'certainly--certainly',
     'father--I',
     'Barashkoff--I',
     'see--and',
     'everything--Lebedeff',
     'about--he',
     'now--I',
     'Lihachof--',
     'Zaleshoff--looking',
     'old--fifty',
     'so--and',
     'this--do',
     'day--not',
     'that--',
    
     'do--by',
     'know--my',
     'illness--I',
     'well--here',
     'fellow--you']
    
    

配方 1-7。处理字符串

这个菜谱讨论了如何处理字符串和文本数据。您可以使用字符串操作进行各种基本的文本探索。

问题

你想探索处理字符串。

解决办法

最简单的方法是使用下面的字符串功能。

  • s.find(t)是 s 中字符串 t 的第一个实例的索引(如果找不到,则为–1)

  • s.rfind(t)是 s 中字符串 t 的最后一个实例的索引(如果找不到,则为–1)

  • s.index(t)类似于s.find(t),除了它在未找到时引发 ValueError

  • s.rindex(t)类似于s.rfind(t),除了它在未找到时引发 ValueError

  • 使用 s 作为粘合剂将文本的单词组合成一个字符串

  • 在找到 t 的地方将 s 分割成一个列表(默认为空白)

  • 将 s 拆分成一个字符串列表,每行一个

  • s.lower()是字符串 s 的小写版本

  • s.upper()是字符串 s 的大写版本

  • s.title()是字符串 s 的带标题的大小写版本

  • s.strip()是没有前导或尾随空白的 s 的副本

  • s.replace(t, u)用 s 中的 u 替换 t 的实例

它是如何工作的

现在让我们来看几个例子。

替换内容

创建一个字符串并替换内容。创建字符串很容易。这是通过用单引号或双引号将字符括起来实现的。而要替换,可以使用replace功能。

  1. 创建一个字符串。

    String_v1 = "I am exploring NLP"
    #To extract particular character or range of characters from string
    print(String_v1[0])
    #output
    "I"
    #To extract the word “exploring”
    print(String_v1[5:14])
    #output
    exploring
    
    
  2. 将前面字符串中的"exploring"替换为"learning"

    String_v2 = String_v1.replace("exploring", "learning")
    print(String_v2)
    #Output
    I am learning NLP
    
    
连接两个字符串

下面是简单的代码。

s1 = "nlp"
s2 = "machine learning"
s3 = s1+s2
print(s3)

#output
'nlpmachine learning'

在字符串中搜索子字符串

使用find函数获取整个字符串中子串的起始索引值。

var="I am learning NLP"
f= "learn"
var.find(f)
#output
5

配方 1-8。从网上抓取文本

这个食谱讨论了如何从网上抓取数据。

Caution

在抓取任何网站、博客或电子商务网站之前,请确保您阅读了该网站是否允许数据抓取的条款和条件。通常,robots.txt 包含条款和条件(例如,参见 www.alixpartners.com/robots.txt ),而站点地图包含 URL 的地图(例如,参见 www.alixpartners.com/sitemap.xml )。

Web 抓取也称为 web 采集和 web 数据提取。它是一种从网站中提取大量数据并保存在数据库或本地的技术。您可以使用这些数据来提取与您的客户、用户或产品相关的信息,从而使企业受益。

对 HTML 有基本的了解是先决条件。

问题

你想通过抓取从网上提取数据。让我们以 IMDB.com 为例来搜集顶级电影。

解决办法

最简单的方法是使用 Python 漂亮的 Soup 或 Scrapy 库。让我们在这个食谱中使用美丽的汤。

它是如何工作的

按照本节中的步骤从 web 中提取数据。

步骤 8-1。安装所有必需的库
!pip install bs4

!pip install requests

步骤 8-2。导入库
from bs4 import BeautifulSoup

import requests
import pandas as pd
from pandas import Series, DataFrame
from ipywidgets import FloatProgress
from time import sleep
from IPython.display import display
import re
import pickle

步骤 8-3。识别提取数据的 URL
url = 'http://www.imdb.com/chart/top?ref_=nv_mv_250_6'

步骤 8-4。使用 Beautiful Soup 请求 URL 并下载内容
result = requests.get(url)
c = result.content

soup = BeautifulSoup(c,"lxml")

步骤 8-5。理解网站的结构以提取所需的信息

转到网站,右键单击页面内容,检查网站的 HTML 结构。

确定要提取的数据和字段。例如,您想要电影名称和 IMDB 分级。

检查 HTML 中的哪个 div 或类包含电影名称,并相应地解析这个美丽的 Soup。在这个例子中,你可以通过<table class ="chart full-width"><td class="titleColumn">解析这个汤来提取电影名。

同样,您可以获取其他数据;请参考步骤 8-6 中的代码。

img/475440_2_En_1_Figa_HTML.jpg

步骤 8-6。使用 Beautiful Soup 从 HTML 标签中提取和解析数据
summary = soup.find('div',{'class':'article'})
# Create empty lists to append the extracted data

.
moviename = []
cast = []
description = []
rating = []
ratingoutof = []
year = []
genre = []
movielength = []
rot_audscore = []
rot_avgrating = []
rot_users = []
# Extracting the required data from the html soup.

rgx = re.compile('[%s]' % '()')
f = FloatProgress(min=0, max=250)
display(f)
for row,i in zip(summary.find('table').findAll('tr'),range(len(summary.find('table').findAll('tr')))):

    for sitem in row.findAll('span',{'class':'secondaryInfo'}).
        s = sitem.find(text=True)
        year.append(rgx.sub(", s))
    for ritem in row.findAll('td',{'class':'ratingColumn imdbRating'}).
        for iget in ritem.findAll('strong').
            rating.append(iget.find(text=True))
            ratingoutof.append(iget.get('title').split(' ', 4)[3])
    for item in row.findAll('td',{'class':'titleColumn'}).
        for href in item.findAll('a',href=True).
            moviename.append(href.find(text=True))
            rurl = 'https://www.rottentomatoes.com/m/'+ href.find(text=True)
            try.
                rresult = requests.get(rurl)
            except requests.exceptions.ConnectionError.
                status_code = "Connection refused"
            rc = rresult.content
            rsoup = BeautifulSoup(rc)
            try:

                rot_audscore.append(rsoup.find('div',{'class':'meter-value'}).find('span',{'class':'superPageFontColor'}).text)
                rot_avgrating.append(rsoup.find('div',{'class':'audience-info hidden-xs superPageFontColor'}).find('div').contents[2].strip())
                rot_users.append(rsoup.find('div',{'class':'audience-info hidden-xs superPageFontColor'}).contents[3].contents[2].strip())
            except AttributeError.
                rot_audscore.append("")
                rot_avgrating.append("")
                rot_users.append("")
            cast.append(href.get('title'))
            imdb = "http://www.imdb.com" + href.get('href')
            try.
                iresult = requests.get(imdb)
                ic = iresult.content

                isoup = BeautifulSoup(ic)
                description.append(isoup.find('div',{'class':'summary_text'}).find(text=True).strip())
                genre.append(isoup.find('span',{'class':'itemprop'}).find(text=True))
                movielength.append(isoup.find('time',{'itemprop':'duration'}).find(text=True).strip())

            except requests.exceptions.ConnectionError.
                description.append("")
                genre.append("")
                movielength.append("")
    sleep(.1)
    f.value = i

请注意,由于以下原因,您很有可能在执行该脚本时遇到错误。

  • 您对 URL 的请求失败。如果是这样,请过一段时间再试一次。这在网络抓取中很常见。

  • 网页是动态的,这意味着 HTML 标签不断变化。研究一下标签,并根据 HTML 对代码做一些小的修改,你就可以开始了。

步骤 8-7。将列表转换为数据框架,并执行符合业务要求的分析
# List to pandas series

moviename = Series(moviename)
cast = Series(cast)
description = Series(description)
rating = Series(rating)
ratingoutof = Series(ratingoutof)
year = Series(year)
genre = Series(genre)
movielength = Series(movielength)
rot_audscore = Series(rot_audscore)
rot_avgrating = Series(rot_avgrating)
rot_users = Series(rot_users)
# creating dataframe and doing analysis
imdb_df = pd.concat([moviename,year,description,genre,movielength,cast,rating,ratingoutof,rot_audscore,rot_avgrating,rot_users],axis=1)
imdb_df.columns = ['moviename','year','description','genre','movielength','cast','imdb_rating','imdb_ratingbasedon','tomatoes_audscore','tomatoes_rating','tomatoes_ratingbasedon']
imdb_df['rank'] = imdb_df.index + 1
imdb_df.head(1)
#output

img/475440_2_En_1_Figb_HTML.jpg

第八步。下载数据框
# Saving the file as CSV.
imdb_df.to_csv("imdbdataexport.csv")

本章实现了从数据源中提取文本数据的大部分技术。在接下来的章节中,您将了解如何探索、处理和清理数据。您还将学习功能工程和构建 NLP 应用程序。

二、探索和处理文本数据

本章讨论预处理文本数据和探索性数据分析的各种方法和技术。它涵盖了以下食谱。

  • 食谱 1。用小写字体书写

  • 食谱 2。删除标点符号

  • 食谱三。停止单词删除

  • 食谱 4。文本标准化

  • 食谱 5。拼写纠正

  • 食谱 6。标记化

  • 食谱 7。堵塞物

  • 食谱 8。词汇化

  • 食谱 9。探索性数据分析

  • 食谱 10。处理表情符号和表情符号

  • 食谱 11。端到端处理流水线

在直接进入食谱之前,让我们先了解一下预处理文本数据的必要性。众所周知,世界上大约 90%的数据是非结构化的,可能以图像、文本、音频和视频的形式存在。文本可以有多种形式,从单个单词的列表到句子,再到包含特殊字符的多个段落(如 tweets 和其他标点符号)。它也可能以 web、HTML、文档等形式出现。而且这些数据从来都不是干净的,包含了大量的噪音。需要对其进行处理,然后执行一些预处理功能,以确保为特征工程和模型构建提供正确的输入数据。如果不对数据进行预处理,任何建立在这些数据之上的算法都不会给企业带来任何价值。这让我们想起了数据科学中非常流行的一句话:“垃圾进,垃圾出。”

预处理包括将原始文本数据转换成可理解的格式。真实世界的数据通常是不完整的、不一致的、充满了大量噪声,并且很可能包含许多错误。预处理是解决这类问题的一种行之有效的方法。数据预处理为进一步处理准备原始文本数据。

食谱 2-1。将文本数据转换为小写

这个菜谱讨论了如何将文本数据小写,以使所有数据具有统一的格式,并确保“nlp”和“NLP”被同等对待。

问题

你想要小写的文本数据。

解决办法

最简单的方法是使用 Python 中默认的lower()函数。

lower()方法将字符串中的所有大写字符转换成小写字符并返回它们。

它是如何工作的

按照本节中的步骤对给定的文本或文档进行小写。这里用的是 Python。

步骤 1-1。读取/创建文本数据

让我们创建一个字符串列表,并将其赋给一个变量。

text=['This is introduction to NLP','It is likely to be useful, to people ','Machine learning is the new electrcity','There would be less hype around AI and more action going forward','python is the best tool!','R is good langauage','I like this book','I want more books like this']
#convert list to data frame
import pandas as pd
df = pd.DataFrame({'tweet':text})
print(df)
#output
                                               tweet
0                        This is introduction to NLP
1               It is likely to be useful, to people
2             Machine learning is the new electrcity
3  There would be less hype around AI and more ac...
4                           python is the best tool!
5                                R is good langauage
6                                   I like this book
7                        I want more books like this

步骤 1-2。对文本数据执行 lower()函数

当只有一个字符串时,直接应用lower()函数如下。

x = 'Testing'
x2 = x.lower()
print(x2)
#output

'testing'

当您想要对数据框执行小写操作时,请按如下方式使用应用函数。

df['tweet'] = df['tweet'].apply(lambda x: " ".join(x.lower() for x in x.split()))
df['tweet']
#output
0                          this is introduction to nlp
1                 it is likely to be useful, to people
2               machine learning is the new electrcity
3    there would be less hype around ai and more ac...
4                             python is the best tool!
5                                  r is good langauage
6                                     i like this book
7                          i want more books like this

或者,您可以使用以下代码:

df['tweet'] = df['tweet'].str.lower()

仅此而已。整个 tweet 列被转换成小写。让我们看看在接下来的食谱中你还能做些什么。

食谱 2-2。删除标点符号

这个食谱讨论了如何从文本数据中删除标点符号。这一步非常重要,因为标点符号不会增加任何额外的信息或价值。因此,删除所有这样的实例减少了数据的大小并提高了计算效率。

问题

您希望从文本数据中删除标点符号。

解决办法

最简单的方法是使用 Python 中的 regex 和replace()函数。

它是如何工作的

按照本节中的步骤删除文本数据中的标点符号。

步骤 2-1。读取/创建文本数据

让我们创建一个字符串列表,并将其赋给一个变量。

text=['This is introduction to NLP','It is likely to be useful, to people ','Machine learning is the new electrcity','There would be less hype around AI and more action going forward','python is the best tool!','R is good langauage','I like this book','I want more books like this']
#convert list to dataframe
import pandas as pd
df = pd.DataFrame({'tweet':text})
print(df)
#output
 tweet
0 This is introduction to NLP
1 It is likely to be useful, to people
2 Machine learning is the new electrcity
3 There would be less hype around AI and more ac...
4 python is the best tool!
5 R is good langauage
6 I like this book
7 I want more books like this

第 2-2 步。对文本数据执行 replace()函数

使用 regex 和replace()函数,您可以删除标点符号,如下所示。

import re
s = "I. like. This book!"
s1 = re.sub(r'[^\w\s]',",s)
s1
#output

'I like This book'

或者:

df['tweet'] = df['tweet'].str.replace('[^\w\s]',")
df['tweet']
#output
0                          this is introduction to nlp
1                  it is likely to be useful to people
2               machine learning is the new electrcity
3    there would be less hype around ai and more ac...
4                              python is the best tool
5                                  r is good langauage
6                                     i like this book
7                          i want more books like this

或者:

import string
s = "I. like. This book!"
for c in string.punctuation:
      s= s.replace(c,"")
s
#output

'I like This book'

食谱 2-3。删除停用词

这个食谱讨论了如何删除停用词。停用词是非常常见的词,与其他关键字相比没有意义或意义较小。如果去掉不常用的词,就可以把重点放在重要的关键词上。例如,在一个搜索引擎中,如果您的搜索查询是“如何使用 Python 开发聊天机器人”,如果搜索引擎试图查找包含单词 howtodevelopchatbotusingpython 的网页,搜索引擎找到的包含 howto 的网页要比包含关于开发聊天机器人的信息的网页多得多因此,如果你删除这些词,搜索引擎可以专注于检索包含关键字开发聊天机器人python 的页面,这将更接近真正感兴趣的页面。同样,你也可以去掉其他常用词和生僻字。

问题

你想删除停用词。

解决办法

最简单的方法是使用 NLTK 库或构建自己的停用词文件。

它是如何工作的

按照本节中的步骤从文本数据中删除停用词。

步骤 3-1。读取/创建文本数据

让我们创建一个字符串列表,并将其赋给一个变量。

text=['This is introduction to NLP','It is likely to be useful, to people ','Machine learning is the new electrcity','There would be less hype around AI and more action going forward','python is the best tool!','R is good langauage','I like this book','I want more books like this']
#convert list to data frame
import pandas as pd
df = pd.DataFrame({'tweet':text})
print(df)
#output
 tweet
0 This is introduction to NLP
1 It is likely to be useful, to people
2 Machine learning is the new electrcity
3 There would be less hype around AI and more ac...
4 python is the best tool!
5 R is good langauage

6 I like this book
7 I want more books like this

第 3-2 步。从文本数据中删除标点符号

使用 NLTK 库,您可以删除标点符号,如下所示。

#install and import libraries
!pip install nltk
import nltk
nltk.download()
from nltk.corpus import stopwords
#remove stop words
stop = stopwords.words('english')
df['tweet'] = df['tweet'].apply(lambda x: " ".join(x for x in x.split() if x not in stop))
df['tweet']
#output
0                                  introduction nlp
1                              likely useful people
2                   machine learning new electrcity
3    would less hype around ai action going forward
4                                  python best tool
5                                  r good langauage

6                                         like book
7                                   want books like

现在没有停止词了。这一步什么都去掉了。

食谱 2-4。标准化文本

这个食谱讨论了如何标准化文本。但在此之前,我们先讨论一下文本标准化以及为什么需要它。大多数文本数据存在于客户评论、博客或推文中,在这些地方,人们很有可能使用短词和缩写来表示相同的意思。这可以帮助下游过程容易地理解和解决文本的语义。

问题

你想要标准化文本。

解决办法

您可以编写自己的自定义词典来查找短单词和缩写。首先,您需要查看数据中是否存在任何短词和缩写。这可以通过查看我们文档中单词的频率分布或在创建自定义词典之前通过单词云可视化来实现。

它是如何工作的

按照本节中的步骤执行文本标准化。

步骤 4-1。创建自定义查找字典

该词典用于根据您的数据进行文本标准化。

lookup_dict = {'nlp':'natural language processing', 'ur':'your', "wbu" : "what about you"}
import re

第 4-2 步。为文本标准化创建自定义函数

代码如下:

def text_std(input_text):
 words = input_text.split()
 new_words = []
 for word in words:
     word = re.sub(r'[^\w\s]',",word)
     if word.lower() in lookup_dict:
         word = lookup_dict[word.lower()]
         new_words.append(word)
         new_text = " ".join(new_words)
 return new_text

第 4-3 步。运行文本 _ 标准函数

输出也需要检查。

text_std("I like nlp it's ur choice")
#output

'natural language processing your'
Here, nlp has standardized to 'natural language processing' and ur to 'your'.

食谱 2-5。纠正拼写

这个食谱讨论了如何进行拼写纠正。但在此之前,我们先来看看为什么这个拼写纠正很重要。大多数文本数据存在于客户评论、博客或推文中,在这些地方,人们很有可能使用短词并犯打字错误。这样就减少了代表同一个意思的单词的多个副本。例如,“processing”和“processing”被视为不同的词,即使在相同的意义上使用。

请注意,缩写应该在这一步之前处理,否则校正器有时会失败。比如说,“ur”(实际上是“你的”)会被更正为“or”

问题

你想做拼写纠正。

解决办法

最简单的方法是使用 TextBlob 库。

它是如何工作的

按照本节中的步骤进行拼写更正。

步骤 5-1。读取/创建文本数据

让我们创建一个字符串列表,并将其赋给一个变量。

text=['Introduction to NLP','It is likely to be useful, to people ','Machine learning is the new electrcity', 'R is good langauage','I like this book','I want more books like this']
#convert list to dataframe
import pandas as pd
df = pd.DataFrame({'tweet':text})
print(df)
#output
                                    tweet
0                     Introduction to NLP
1    It is likely to be useful, to people
2  Machine learning is the new electrcity
3                     R is good langauage
4                        I like this book
5             I want more books like this

第 5-2 步。对文本数据执行拼写纠正

使用 TextBlob,您可以进行拼写,如下所示。

#Install textblob library
!pip install textblob

#import libraries and use 'correct' function
from textblob import TextBlob
df['tweet'].apply(lambda x: str(TextBlob(x).correct()))
#output
0                        Introduction to NLP
1       It is likely to be useful, to people
2    Machine learning is the new electricity
3                         R is good language
4                           I like this book
5                I want more books like this

请注意,electricity的拼写和语言已被更正。

#You can also use autocorrect library as shown below
#install autocorrect
!pip install autocorrect
from autocorrect import spell
print(spell(u'mussage'))
print(spell(u'sirvice'))

#output
'message'
'service'

配方 2-6。标记文本

这个食谱着眼于标记化的方法。标记化是指将文本分割成最小的有意义的单元。有一个句子分词器和一个单词分词器。你在这个食谱中看到一个单词分词器。对于任何类型的分析,这都是文本预处理中必不可少的步骤。有许多库可以执行标记化,如 NLTK、spaCy 和 TextBlob。这里有几种方法可以实现。

问题

你想做记号化。

解决办法

最简单的方法是使用 TextBlob 库。

它是如何工作的

按照本节中的步骤执行标记化。

步骤 6-1。读取/创建文本数据

让我们创建一个字符串列表,并将其赋给一个变量。

text=['This is introduction to NLP','It is likely to be useful, to people ','Machine learning is the new electrcity','There would be less hype around AI and more action going forward','python is the best tool!','R is good langauage','I like this book','I want more books like this']
#convert list to dataframe
import pandas as pd
df = pd.DataFrame({'tweet':text})
print(df)
#output
 tweet
0 This is introduction to NLP

1 It is likely to be useful, to people
2 Machine learning is the new electrcity
3 There would be less hype around AI and more ac...
4 python is the best tool!
5 R is good langauage
6 I like this book
7 I want more books like this

第 6-2 步。将文本数据标记化

标记化的结果是一个标记列表。

#Using textblob
from textblob import TextBlob
TextBlob(df['tweet'][3]).words

#output
WordList(['would', 'less', 'hype', 'around', 'ai', 'action', 'going', 'forward'])
#using NLTK
import nltk
#create data
mystring = "My favorite animal is cat"
nltk.word_tokenize(mystring)
#output

['My', 'favorite', 'animal', 'is', 'cat']
#using split function from python
mystring.split()
#output
['My', 'favorite', 'animal', 'is', 'cat']

食谱 2-7。堵塞物

这个食谱讨论词干。词干提取是提取词根的过程。比如被词干化为

问题

你想做词干分析。

解决办法

最简单的方法是使用 NLTK 或 TextBlob 库。

它是如何工作的

按照本节中的步骤执行词干分析。

步骤 7-1。读取文本数据

让我们创建一个字符串列表,并将其赋给一个变量。

text=['I like fishing','I eat fish','There are many fishes in pound']
#convert list to dataframe
import pandas as pd
df = pd.DataFrame({'tweet':text})
print(df)
#output
                            tweet
0                  I like fishing
1                      I eat fish
2  There are many fishes in pound

第 7-2 步。阻止文本

对文本数据执行以下代码。

#Import library

from nltk.stem import PorterStemmer
st = PorterStemmer()
df['tweet'][:5].apply(lambda x: " ".join([st.stem(word) for word in x.split()]))
#output
0                     I like fish
1                      I eat fish
2    there are mani fish in pound

注意,fish、fishing 和 fish 都被词干化为 fish。

食谱 2-8。词汇化

这个食谱讨论了词汇化,即通过考虑词汇表提取词根的过程。比如好的更好的,或者最好的被词条化为好的

词的词性是在词条化中确定的。它返回单词的字典形式,该形式必须有效。而词干提取只是提取词根。

  • 简化处理匹配以及匹配

  • 炮泥手柄将匹配。

引理化可以得到更好的结果。

  • 的词干形式为

  • 的词干形式是

  • 的词汇化形式为

  • 的词汇化形式为

问题

你想进行词汇化。

解决办法

最简单的方法是使用 NLTK 或 TextBlob 库。

它是如何工作的

按照本节中的步骤执行术语化。

步骤 8-1。读取文本数据

让我们创建一个字符串列表,并将其赋给一个变量。

text=['I like fishing','I eat fish','There are many fishes in pound', 'leaves and leaf']
#convert list to dataframe
import pandas as pd
df = pd.DataFrame({'tweet':text})
print(df)
                                tweet
0                      I like fishing
1                          I eat fish
2  There are multiple fishes in pound
3                     leaves and leaf

步骤 8-2。将数据符号化

对文本数据执行以下代码。

#Import library
from textblob import Word
#Code for lemmatize
df['tweet'] = df['tweet'].apply(lambda x: " ".join([Word(word).lemmatize() for word in x.split()]))
df['tweet']
#output

0                      I like fishing
1                          I eat fish
2    There are multiple fish in pound
3                       leaf and leaf

你可以观察到,鱼和鱼都被旅鼠化为鱼,叶子和叶子都被旅鼠化为叶子。

食谱 2-9。浏览文本数据

到目前为止,您应该已经熟悉了数据收集和文本预处理。让我们进行一些探索性的数据分析。

问题

你想要探索和理解文本数据。

解决办法

最简单的方法是使用 NLTK 或 TextBlob 库。

它是如何工作的

遵循此过程中的步骤。

步骤 9-1。读取文本数据

如果您还没有下载数据集,请执行以下代码下载数据集。

nltk.download().
#Importing data
import nltk
from nltk.corpus import webtext
nltk.download('webtext')
wt_sentences = webtext.sents('firefox.txt')
wt_words = webtext.words('firefox.txt')

步骤 9-2。导入必要的库

用于计算频率的导入库:

from nltk.probability import FreqDist
from nltk.corpus import stopwords
import string

步骤 9-3 检查数据中的字数

数数单词的数量:

len(wt_sentences)
#output
1142
len(wt_words)
#output
102457

步骤 9-4。计算评论中所有单词的频率

为所有单词生成频率:

frequency_dist = nltk.FreqDist(wt_words)
frequency_dist
#showing only top few results
FreqDist({'slowing': 1,
          'warnings': 6,
          'rule': 1,
          'Top': 2,
          'XBL': 12,
          'installation': 44,
          'Networking': 1,
          'inccorrect': 1,
          'killed': 3,
          ']"': 1,
          'LOCKS': 1,
          'limited': 2,
          'cookies': 57,
          'method': 12,
          'arbitrary': 2,
          'b': 3,
          'titlebar': 6,
sorted_frequency_dist =sorted(frequency_dist,key=frequency_dist.__getitem__, reverse=True)
sorted_frequency_dist

['.',
 'in',
 'to',
 '"',
 'the',
 "'",
 'not',
 '-',
 'when',
 'on',
 'a',
 'is',
 't',

 'and',
 'of',

第 9-5 步。考虑长度大于 3 的单词并绘图

我们只考虑频率大于三的词。

large_words = dict([(k,v) for k,v in frequency_dist.items() if len(k)>3])
frequency_dist = nltk.FreqDist(large_words)
frequency_dist.plot(50,cumulative=False)
#output

img/475440_2_En_2_Figa_HTML.jpg

第 9-6 步。构建单词云

单词云是最频繁重复的单词的图形表示。

#install library

!pip install wordcloud
#build wordcloud
from wordcloud import WordCloud
wcloud = WordCloud().generate_from_frequencies(frequency_dist)
#plotting the wordcloud
import matplotlib.pyplot as plt
plt.imshow(wcloud, interpolation="bilinear")
plt.axis("off")
(-0.5, 399.5, 199.5, -0.5)
plt.show()
#output

img/475440_2_En_2_Figb_HTML.jpg

接下来,让我们删除停用词,然后建立词云。输出应该类似于下一个菜谱中显示的内容。

img/475440_2_En_2_Figc_HTML.jpg

配方 2-10。处理表情符号和表情符号

什么是表情符号?表情符号这个词本质上是“形象人物”的意思(来源于日语 e 意为“形象:莫吉意为“字母人物”)。什么是表情?:):-]表情符号代表一个人的面部表情,只使用键盘字符,如字母、数字和标点符号。

在今天的网络世界中,表情符号和表情符号是主要的语言,当我们需要快速准确地与全球任何人交流时,它们可以让我们与他们交流。表情符号和表情符号在文本分析中都起着重要的作用。它们最常用于社交媒体、电子邮件和短信,尽管它们可以在任何类型的电子通信中找到。在情感没有用的情况下,你可能需要把它们从你的文本分析中去除。另一方面,您应该保留它们,因为它们提供了有价值的信息,尤其是在情感分析中,删除它们可能不是一个合适的解决方案;例如,如果一家公司想知道人们对社交媒体上的新产品、新活动或品牌的感受。

表情符号通过想象用户的情绪、态度和观点,帮助识别消费者参与度需要提高的地方。这提供了重要的信息,对于任何企业来说,更好地理解客户的感受都是至关重要的。表情符号和表情符号数据的收集和分析为公司提供了有用的信息。它们可以转换成 word 格式,用于建模过程。在这本书里,你看到了如何用 Python 保存 word 格式的表情符号和表情符号。

这本书用了一个叫 emot 的库。

问题

你想用一个相关的、有意义的词来代替表情符号。

解决办法

最简单的方法就是使用 emot 库。

它是如何工作的

遵循以下步骤。

步骤 10-A1。读取文本数据

img/475440_2_En_2_Figd_HTML.png

步骤 10-A2。安装并导入必要的库
#Installing emot library

!pip install emot

#Importing libraries
import re
from emot.emo_unicode import UNICODE_EMO, EMOTICONS

步骤 10-A3。写一个把表情符号转换成单词的函数
# Function for converting emojis into word

def converting_emojis(text):
    for emot in UNICODE_EMO:
        text = text.replace(emot, "_".join(UNICODE_EMO[emot].replace(",","").replace(":","").split()))
    return text

步骤 10-A4。将带有表情符号的文本传递给函数
converting_emojis(text1) 

#output
What are you saying face_with_tears_of_joy. I am the boss smiling_face_with_sunglasses, and why are you so unamused_face

问题

你想移除表情符号

解决办法

最简单的方法是使用 Unicode。

它是如何工作的

遵循以下步骤。

步骤 10-B1。读取文本数据

img/475440_2_En_2_Fige_HTML.png

第十步-B2。安装并导入必要的库
#Importing libraries
import re

from emot.emo_unicode import UNICODE_EMO, EMOTICONS

第十步-B3。写一个移除表情符号的函数
def emoji_removal(string)

:
    emoji_unicodes = re.compile("["
                               u"\U0001F600-\U0001F64F"  # emoticons
                               u"\U0001F300-\U0001F5FF"  # symbols
                               u"\U0001F680-\U0001F6FF"  # transport
                               u"\U0001F1E0-\U0001F1FF"  # flags (iOS)
                               u"\U00002500-\U00002BEF"
                               u"\U00002702-\U000027B0"
                               u"\U000024C2-\U0001F251"
                               u"\U0001f926-\U0001f937"
                               u"\U00010000-\U0010ffff"
                               u"\u2640-\u2642"
                               u"\u2600-\u2B55"
                               u"\u200d"
                               u"\u23cf"
                               u"\u23e9"
                               u"\u231a"
                               u"\ufe0f"
                               u"\u3030"
                               "]+", flags=re.UNICODE)
    return emoji_unicodes.sub(r'', string)

步骤 10-B4。将带有表情符号的文本传递给函数
emoji_removal(text1)

#output

What are you saying. I am the boss, and why are you so emoji_removal

问题

你想用相关的,有意义的单词替换表情符号。

解决办法

最简单的方法就是使用 emot 库。

它是如何工作的

遵循以下步骤。

第十步-C1。读取文本数据
#create sample text data with emoticons

text2 = "Hey, how are you :-) how was your day, what are you doing?:-)"

第十步-C2。安装并导入必要的库
#Installing emot library

!pip install emot
#Importing libraries
import re
from emot.emo_unicode import UNICODE_EMO, EMOTICONS

第十步-C3。编写将表情符号转换为文字的功能
# Function to convert emoticons into word

def converting_emoticons(text):
    for emot in EMOTICONS:
        text = re.sub(u'('+emot+')', "_".join(EMOTICONS[emot].replace(",","").split()), text)
    return text

第十步-C4。将带有表情符号的文本传递给函数
converting_emoticons(text2)

#output

Hey, how are you Happy_face_smiley how was your day, what are you doing? Happy_face_smiley"

问题

您想删除表情图标吗

解决办法

最简单的方法是使用 Unicode。移除表情符号和表情符号的代码保持不变;但是,您需要添加各自的 Unicode。

它是如何工作的

遵循以下步骤。

步骤 10-D1 读取文本数据
#create sample text data with emoticons

text2 = "Hey, how are you :-) how was your day, what are you doing?:-)"

第十步-D2。安装并导入必要的库
#Importing libraries
import re
from emot.emo_unicode import UNICODE_EMO, EMOTICONS

步骤 10-D3。写函数去掉表情
def removing_emoticons(string)

:
    emot_unicodes = re.compile("["
                               u"\U0001F600-\U0001F64F"  # emoticons
                               u"\U0001F300-\U0001F5FF"  # symbols
                               u"\U0001F680-\U0001F6FF"  # transport
                               u"\U0001F1E0-\U0001F1FF"  # flags (iOS)
                               u"\U00002500-\U00002BEF"
                               u"\U00002702-\U000027B0"
                               u"\U000024C2-\U0001F251"
                               u"\U0001f926-\U0001f937"
                               u"\U00010000-\U0010ffff"
                               u"\u2640-\u2642"
                               u"\u2600-\u2B55"
                               u"\u200d"
                               u"\u23cf"
                               u"\u23e9"
                               u"\u231a"
                               u"\ufe0f"
                               u"\u3030"
                               "]+", flags=re.UNICODE)

    return emot_unicodes.sub(r'', string)

第十步-D4。将带有表情符号的文本传递给函数
removing_emoticons(text2)

#output

Hey, how are you how was your day, what are you doing?"

问题

找到检测表情符号并确定其含义的库。

解决办法

你可以使用 demoji 库。

它是如何工作的

遵循以下步骤。

第十步-E1。读取文本数据

img/475440_2_En_2_Figf_HTML.png

步骤 10-E2。安装并导入必要的库
#Installing & Importing libraries
!pip install demoji
import demoji
demoji.download_codes()

第十步-E3。找到所有表情符号并确定它们的含义

img/475440_2_En_2_Figg_HTML.png

食谱 2-11。构建文本预处理管道

到目前为止,您已经完成了大部分的文本操作和处理技术和方法。让我们在这个食谱中做一些有趣的事情。

问题

您希望构建一个端到端的文本预处理管道。每当您想要对任何 NLP 应用程序进行预处理时,您可以直接将数据插入这个管道函数,并获得所需的干净文本数据作为输出。

解决办法

最简单的方法是使用您到目前为止学到的所有技术创建一个自定义函数。

它是如何工作的

它的工作原理是将所有可能的处理技术放入一个包装器函数中,并通过它传递数据。

步骤 11-1。读取/创建文本数据

让我们创建一个字符串列表,并将其赋给一个变量——也许是一条样本 tweet。

tweet_sample= "How to take control of your #debt https://personal.vanguard.com/us/insights/saving-investing/debt-management.#Best advice for #family #financial #success (@PrepareToWin)"

你也可以使用你在第一章中提取的 Twitter 数据。

步骤 11-2。处理文本

执行下面的函数来处理 tweet。

def processRow(row):
    import re

    import nltk
    from textblob import TextBlob
    from nltk.corpus import stopwords
    from nltk.stem import PorterStemmer
    from textblob import Word
    from nltk.util import ngrams
    import re
    from wordcloud import WordCloud, STOPWORDS
    from nltk.tokenize import word_tokenize
    tweet = row
    #Lower case
    tweet.lower()
    #Removes unicode strings like "\u002c" and "x96"
    tweet = re.sub(r'(\\u[0-9A-Fa-f]+)', "r", tweet)
    tweet = re.sub(r'[^\x00-\x7f]', "r",tweet)
    #convert any url to URL
    tweet = re.sub('((www\.[^\s]+)|(https?://[^\s]+))','URL',tweet)
    #Convert any @Username to "AT_USER"
    tweet = re.sub('@[^\s]+','AT_USER',tweet)
    #Remove additional white spaces
    tweet = re.sub('[\s]+', ' ', tweet)
    tweet = re.sub('[\n]+', ' ', tweet)
    #Remove not alphanumeric symbols white spaces
    tweet = re.sub(r'[^\w]', ' ', tweet)
    #Removes hastag in front of a word """
    tweet = re.sub(r'#([^\s]+)', r'\1', tweet)
    #Replace #word with word
    tweet = re.sub(r'#([^\s]+)', r'\1', tweet)
    #Remove :( or :)

    tweet = tweet.replace(':)',")
    tweet = tweet.replace(':(',")
    #remove numbers
    tweet = ".join([i for i in tweet if not i.isdigit()])
    #remove multiple exclamation
    tweet = re.sub(r"(\!)\1+", ' ', tweet)
    #remove multiple question marks
    tweet = re.sub(r"(\?)\1+", ' ', tweet)
    #remove multistop

    tweet = re.sub(r"(\.)\1+", ' ', tweet)
    #lemma
    from textblob import Word
    tweet =" ".join([Word(word).lemmatize() for word in tweet.split()])
    #stemmer

    #st = PorterStemmer()
    #tweet=" ".join([st.stem(word) for word in tweet.split()])
    #Removes emoticons from text
    tweet = re.sub(':\)|;\)|:-\)|\(-:|:-D|=D|:P|xD|X-p|\^\^|:-*|\^\.\^|\^\-\^|\^\_\^|\,-\)|\)-:|:\'\(|:\(|:-\(|:\S|T\.T|\.\_\.|:<|:-\S|:-<|\*\-\*|:O|=O|=\-O|O\.o|XO|O\_O|:-\@|=/|:/|X\-\(|>\.<|>=\(|D:', ", tweet)
    #trim
    tweet = tweet.strip('\'"')
    row = tweet
    return row
#call the function with your data
processRow(tweet_sample)

#output
'How to take control of your debt URL Best advice for family financial success AT_USER'

到目前为止,您已经学习了如何读取文本数据,然后处理和清理它。下一章着眼于将文本转换成构建 NLP 应用程序的有意义的特征。