当前位置: 首页 > 科技观察

如何用Python清理文本数据?

时间:2023-03-20 20:06:05 科技观察

并非所有数据格式都会采用表格格式。随着我们进入大数据时代,数据的形式非常多样化,包括图像、文本、图形等等。由于一种数据与另一种数据的格式非常不同,因此非常有必要将这些数据预处理成计算机可读的格式。在本文中,我们将展示如何使用Python预处理文本数据,我们需要使用NLTK和re-library库。过程1.文本小写在我们开始处理文本之前,最好先将所有字符小写。我们这样做的原因是为了避免区分大小写的过程。假设我们要去除字符串中的停用词,正常的操作是将非停用词组合成一个句子。如果没有小写字母,则无法检测到停用词并将产生相同的字符串。这就是小写文本如此重要的原因。在Python中很容易做到这一点。代码是这样的:#samplex="WatchThisAirportGetSwallowedUpByASandstormInUnderAMinutehttp://t.co/TvYQczGJdy"#小写文本x=x.lower()print(x)>>>watchthisairportgetswallowedupbyasandstorminunderaminutehttp://t.co/tvyqczgjdy2.DeleteUnicode字符有些文章可能包含Unicode字符,当我们在ASCII格式上看到它时是不可读的。大多数时候,这些字符用于表情符号和非ASCII字符。要删除该字符,我们可以使用如下代码:#examplex="RedditWillNowQuarantine?_http://t.co/pkUAMXw6pm#onlinecommunities#reddit#amageddon#freespeech#Businesshttp://t.co/PAWvNJ4sAP"#Removeunicodecharacterx=x.encode('ascii','ignore').decode()print(x)>>>RedditWillNowQuarantine_http://t.co/pkUAMXw6pm#onlinecommunities#reddit#amageddon#freespeech#Businesshttp://t.co/PAWvNJ4sAP3。删除停用词停用词是一种对文本含义没有显着贡献的词。因此,我们可以去掉这些词。要检索停用词,我们可以从NLTK库中下载一个库。下面是实现代码:importnltknltk.download()#只下载所有nltkstop_words=stopwords.words("english")#例子x="AmericalikeSouthAfricaisatraumatisedsickcountry-indifferentwaysofcourse-butstillmessedup."#删除停用词x=''.join([wordforwordinx.split('')ifwordnotinstop_words])print(x)>>>AmericalikeSouthAfricatraumatisickcountry-differentwayscourse-stillmessedup。4.删除提及项、标签、链接等术语。除了删除Unicode和停用词外,还有几个术语需要删除,包括提及项、散列标记、链接、标点符号等。要摆脱这些,如果我们仅仅依靠已经定义好的字符是很难进行这些操作的。因此,我们需要通过正则表达式(Regex)来匹配我们想要的term的模式。Regex是一个特殊的字符串,它包含一个模式,该模式匹配与该模式关联的单词。使用名为re的Python库搜索或删除这些模式。下面是实现代码:importre#Deletementionx="@DDNewsLive@NitishKumarand@ArvindKejriwalcan'tsurvivewithoutreferring@@narendramodi.WithoutMrModitheyareBIGZEROS"x=re.sub("@\S+","",x)print(x)>>>并且没有参考就无法生存。WithoutMrModitheyareBIGZEROS#DeleteURL链接x="SevereThunderstormpicturesfromacrosstheMid-Southhttp://t.co/UZWLgJQzNS"x=re.sub("https*\S+","",x)print(x)>>>SevereThunderstormpicturesfromacrosstheMid-South#Removelabelx="Arepeoplenotconcernedthatafter#SLAB'sobliterationinScotland#LabourUKisrippingitsselfapartover#Labourleadershipcontest?"x=re.sub("#\S+","",x)print(x)>>>ArepeoplenotconcernedthatafterobliterationinScotlandUK是下一个字符x="Notley'stactfulyetverydirectresponsetoHarper'sattackonAlberta'sgov't.HellYEAHPremier!http://t.co/rzSUlzMOkX#ableg#cdnpoli"x=re.sub("\'\w+",'',x)print(x)>>>诺特尔ytactfulyetverydirectresponsetoHarperattackonAlbertagov.HellYEAHPremier!http://t.co/rzSUlzMOkX#ableg#cdnpoli#removepunctuationx="In2014IwillonlysmokecrqckifIbecymeamayor.ThisincludesFoursquare."x=re.sub('[%s]'%re.puncpetusation(string),'',x)print(x)>>>In2014IwillonlysmokecrqckifIbecymeamayor.ThisincludesFoursquare.#Deletenumberx="C-130speciallymodifiedtolandinastadiumandrescuehostagesinIranin1980...http://t.co/tNI92fea3uhttp://t.co/czBaMzq3gL"x=re。sub(r'\w*\d+\w*','',x)print(x)>>>C-专门修改为伊朗体育场和救援主机...http://t.co/http://t.co/#替换空格x="andcan'tsurvivewithoutreferring.WithoutMrModitheyareBIGZEROS"x=re.sub('\s{2,}',"",x)print(x)>>>andcan'survivewithoutreferring.WithoutMrModitheyareBIGZEROS5.在文本预处理的每一步之后,让我们将其应用于列表。如果仔细查看这些步骤,您会发现每个方法实际上都是相互关联的。因此,它必须应用于函数,以便我们可以同时按顺序处理所有问题。在应用预处理步骤之前,以下是文本示例:OurDeedsaretheReasonofthis#earthquakeMayALLAHForgiveusallForestfirenearLaRongeSask.CanadaAllresidentsaskedto'shelterinplace'arebeingnotifiedbyofficers.Nootherevacuationorshelterinplaceordersareexpected13,000peoplereceive#wildfiresevacuationordersinCaliforniaJustgotsentthisphotofromRuby#Alaskaassmokefrom#wildfirespoursintoaschool在预处理文本列表时,我们应先执行几个步骤:创建包含所有预Afunctionthatprocessesthesteps,andreturnsthepreprocessedstring.Useamethodcalled"apply"toapplythefunction,andusethattochainliststogether.Thecodeisasfollows:#Incaseofimporterrors#!pipinstallnltk#!pipinstalltextblobimportnumpyasnpimportmatplotlib.pyplotaspltimportpandasaspdimportreimportnltkimportstringfromnltk.corpusimportstopwords##ifmissingcorpus#downloadall-nltknltk.download()df=pd.read_csv('train.wordsv=')stopwords("english")wordnet=WordNetLemmatizer()deftext_preproc(x):x=x.lower()x=''.join([wordforwordinx.split('')ifwordnotinstop_words])x=x.encode('ascii','ignore').decode()x=re.sub(r'https*\S+','',x)x=re.sub(r'@\S+','',x)x=re.sub(r'#\S+','',x)x=re.sub(r'\'\w+','',x)x=re.sub('[%s]'%re.escape(string.punctuation),'',x)x=re.sub(r'\w*\d+\w*','',x)x=re.sub(r'\s{2,}','',x)returnxdf['clean_text']=df.text.apply(text_preproc)上面的文本预处理结果如下:deedsreasonmayallahforgiveusforestfirenearlarongesaskcanadaresidentsaskedplacenotifiedofficersevacuationshelterplaceordersexpectedpeoplereceiveevacuationorderscaliforniagotsentphotorubysmokepoursschool最后以上内容就是使用Python进行文本预处理的具体步骤,希望能够帮助大家用它来解决与Issuesrelatedtotextdata,improvingthenormativenessoftextdataandmodels的准确性