如何用Python清理文本数据?

开发 后端
不是所有数据格式都会采用表格格式。随着我们进入大数据时代,数据的格式非常多样化,包括图像、文本、图形等等。

 不是所有数据格式都会采用表格格式。随着我们进入大数据时代,数据的格式非常多样化,包括图像、文本、图形等等。

因为格式非常多样,从一个数据到另一个数据,所以将这些数据预处理为计算机可读的格式是非常必要的。

在本文中,将展示如何使用Python预处理文本数据,我们需要用到 NLTK 和 re-library 库。

 

如何用Python清理文本数据?

 

过程

1.文本小写

在我们开始处理文本之前,最好先将所有字符都小写。我们这样做的原因是为了避免区分大小写的过程。

假设我们想从字符串中删除停止词,正常操作是将非停止词合并成一个句子。如果不使用小写,则无法检测到停止词,并将导致相同的字符串。这就是为什么降低文本大小写这么重要了。

用Python实现这一点很容易。代码是这样的:

 

  1. # 样例 
  2. x = "Watch This Airport Get Swallowed Up By A Sandstorm In Under A Minute http://t.co/TvYQczGJdy" 
  3. # 将文本小写 
  4. x = x.lower() 
  5. print(x) 
  6. >>> watch this airport get swallowed up by a sandstorm in under a minute http://t.co/tvyqczgjdy 

 

2.删除 Unicode 字符

一些文章中可能包含 Unicode 字符,当我们在 ASCII 格式上看到它时,它是不可读的。大多数情况下,这些字符用于表情符号和非 ASCII 字符。要删除该字符,我们可以使用这样的代码:

 

  1. # 示例 
  2. x = "Reddit Will Now Quarantine‰Û_ http://t.co/pkUAMXw6pm #onlinecommunities #reddit #amageddon #freespeech #Business http://t.co/PAWvNJ4sAP" 
  3. # 删除 unicode 字符 
  4. x = x.encode('ascii''ignore').decode() 
  5. print(x) 
  6. >>> Reddit Will Now Quarantine_ http://t.co/pkUAMXw6pm #onlinecommunities #reddit #amageddon #freespeech #Business http://t.co/PAWvNJ4sAP 

 

3.删除停止词

停止词是一种对文本意义没有显著贡献的词。因此,我们可以删除这些词。为了检索停止词,我们可以从 NLTK 库中下载一个资料库。以下为实现代码:

 

  1. import nltk 
  2. nltk.download() 
  3. # 只需下载所有nltk 
  4. stop_words = stopwords.words("english"
  5. # 示例 
  6. x = "America like South Africa is a traumatised sick country - in different ways of course - but still messed up." 
  7. # 删除停止词 
  8. x = ' '.join([word for word in x.split(' ') if word not in stop_words]) 
  9. print(x) 
  10. >>> America like South Africa traumatised sick country - different ways course - still messed up. 

 

4.删除诸如提及、标签、链接等术语。

除了删除 Unicode 和停止词外,还有几个术语需要删除,包括提及、哈希标记、链接、标点符号等。

要去除这些,如果我们仅依赖于已经定义的字符,很难做到这些操作。因此,我们需要通过使用正则表达式(Regex)来匹配我们想要的术语的模式。

Regex 是一个特殊的字符串,它包含一个可以匹配与该模式相关联的单词的模式。通过使用名为 re. 的 Python 库搜索或删除这些模式。以下为实现代码:

 

  1. import re 
  2. # 删除提及 
  3. x = "@DDNewsLive @NitishKumar  and @ArvindKejriwal can't survive without referring @@narendramodi . Without Mr Modi they are BIG ZEROS" 
  4. x = re.sub("@\S+"" ", x) 
  5. print(x) 
  6. >>>      and   can't survive without referring   . Without Mr Modi they are BIG ZEROS 
  7. # 删除 URL 链接 
  8. x = "Severe Thunderstorm pictures from across the Mid-South http://t.co/UZWLgJQzNS" 
  9. x = re.sub("https*\S+"" ", x) 
  10. print(x) 
  11. >>> Severe Thunderstorm pictures from across the Mid-South 
  12. # 删除标签 
  13. x = "Are people not concerned that after #SLAB's obliteration in Scotland #Labour UK is ripping itself apart over #Labourleadership contest?" 
  14. x = re.sub("#\S+"" ", x) 
  15. print(x) 
  16. >>> Are people not concerned that after   obliteration in Scotland   UK is ripping itself apart over   contest? 
  17. # 删除记号和下一个字符 
  18. x = "Notley's tactful yet very direct response to Harper's attack on Alberta's gov't. Hell YEAH Premier! http://t.co/rzSUlzMOkX #ableg #cdnpoli" 
  19. x = re.sub("\'\w+", '', x) 
  20. print(x) 
  21. >>> Notley tactful yet very direct response to Harper attack on Alberta gov. Hell YEAH Premier! http://t.co/rzSUlzMOkX #ableg #cdnpoli 
  22. # 删除标点符号 
  23. x = "In 2014 I will only smoke crqck if I becyme a mayor. This includes Foursquare." 
  24. x = re.sub('[%s]' % re.escape(string.punctuation), ' ', x) 
  25. print(x) 
  26. >>> In 2014 I will only smoke crqck if I becyme a mayor. This includes Foursquare. 
  27. # 删除数字 
  28. x = "C-130 specially modified to land in a stadium and rescue hostages in Iran in 1980... http://t.co/tNI92fea3u http://t.co/czBaMzq3gL" 
  29. x = re.sub(r'\w*\d+\w*''', x) 
  30. print(x) 
  31. >>> C- specially modified to land in a stadium and rescue hostages in Iran in ... http://t.co/ http://t.co/ 
  32. #替换空格 
  33. x = "     and   can't survive without referring   . Without Mr Modi they are BIG ZEROS" 
  34. x = re.sub('\s{2,}'" ", x) 
  35. print(x) 
  36. >>>  and can't survive without referring . Without Mr Modi they are BIG ZEROS 

 

5.功能组合

在我们了解了文本预处理的每个步骤之后,让我们将其应用于列表。如果仔细看这些步骤,你会发现其实每个方法都是相互关联的。因此,必须将其应用于函数,以便我们可以按顺序同时处理所有问题。在应用预处理步骤之前,以下是文本示例:

 

  1. Our Deeds are the Reason of this #earthquake May ALLAH Forgive us all 
  2. Forest fire near La Ronge Sask. Canada 
  3. All residents asked to 'shelter in place' are being notified by officers. No other evacuation or shelter in place orders are expected 
  4. 13,000 people receive #wildfires evacuation orders in California  
  5. Just got sent this photo from Ruby #Alaska as smoke from #wildfires pours into a school 

 

在预处理文本列表时,我们应先执行几个步骤:

  • 创建包含所有预处理步骤的函数,并返回预处理的字符串
  • 使用名为"apply"的方法应用函数,并使用该方法将列表链接在一起。

代码如下:

 

  1. # 导入错误的情况下 
  2. # ! pip install nltk 
  3. # ! pip install textblob 
  4. import numpy as np 
  5. import matplotlib.pyplot as plt 
  6. import pandas as pd 
  7. import re 
  8. import nltk 
  9. import string 
  10. from nltk.corpus import stopwords 
  11. # # 如果缺少语料库 
  12. # 下载 all-nltk 
  13. nltk.download() 
  14. df = pd.read_csv('train.csv'
  15. stop_words = stopwords.words("english"
  16. wordnet = WordNetLemmatizer() 
  17. def text_preproc(x): 
  18.   x = x.lower() 
  19.   x = ' '.join([word for word in x.split(' ') if word not in stop_words]) 
  20.   x = x.encode('ascii''ignore').decode() 
  21.   x = re.sub(r'https*\S+'' ', x) 
  22.   x = re.sub(r'@\S+'' ', x) 
  23.   x = re.sub(r'#\S+'' ', x) 
  24.   x = re.sub(r'\'\w+''', x) 
  25.   x = re.sub('[%s]' % re.escape(string.punctuation), ' ', x) 
  26.   x = re.sub(r'\w*\d+\w*''', x) 
  27.   x = re.sub(r'\s{2,}'' ', x) 
  28.   return x 
  29. df['clean_text'] = df.text.apply(text_preproc) 

 

 

上面的文本预处理结果如下:

  1. deeds reason may allah forgive us 
  2. forest fire near la ronge sask canada 
  3. residents asked place notified officers evacuation shelter place orders expected 
  4.  people receive evacuation orders california  
  5. got sent photo ruby smoke pours school 

最后

以上内容就是使用 Python 进行文本预处理的具体步骤,希望能够帮助大家用它来解决与文本数据相关的问题,提高文本数据的规范性以及模型的准确度。

责任编辑:华轩 来源: 今日头条
相关推荐

2023-02-08 07:44:56

Pandas数据分析

2021-03-28 08:57:57

Python 文本数据

2011-04-08 14:45:08

文本数据Oracle

2020-07-10 09:49:53

数据清理数据分析查找异常

2019-01-15 14:21:13

Python数据分析数据

2023-06-11 17:00:06

2011-09-19 18:49:33

Vista

2017-11-03 12:57:06

机器学习文本数据Python

2023-11-07 08:33:08

2023-02-08 07:09:40

PythonChatGPT语言模型

2018-03-27 18:12:12

PythonHTML

2016-11-16 15:05:42

情感分析

2020-11-02 08:15:00

Python数据开发

2021-03-18 10:21:45

数据科学大数据机器学习

2021-12-02 09:00:00

数据库NoSQLWeb

2022-06-27 17:40:14

大数据数据科学

2016-02-17 15:15:01

2018-05-17 10:05:24

运行iPadPython

2019-11-28 09:23:17

Python机器学习数据库

2020-05-09 10:38:31

Python透视表数据
点赞
收藏

51CTO技术栈公众号