Python網頁清洗

2021-10-13 19:42:17 字數 3551 閱讀 6185

網頁清洗

題目python網頁清洗

設計在進行自然語言分析時,使用n-gram或者尋找常用片語,可以很容易地把一句話分解成若干個文字片段。通過例項**獲取合理的n-gram,下面的**將返回維基百科詞條「python programming language」的2-gram列表:

實現from urllib.request import urlopen

from bs4 import beautifulsoup

def ngrams(input,n):

input=input.split(' ')

output=

for i in range(len(input)-n+1):

return output
html=urlopen(「

bsobj=beautifulsoup(html,「html.parser」)

content=bsobj.find(「div」,).get_text()

ngrams=ngrams(content,2)

print(ngrams)

print(「2-grams count is :」+str(len(ngrams)))

**執行結果如下:

但是,從結果中可以發現,程式執行後會返回一些很有意思同時也很有用的2-gram序列: [『software』, 『foundation』]。同時也會出現一些凌亂的資料:[『years』, 『ago\xa0(1991-02-20)[1]\n\n\n\n\n\nstable』]。下面我們通過一些正規表示式來移除轉移字元(\n),再把unicode字元過濾掉。使用下面的改進後的程式:

from urllib.request import urlopen

from bs4 import beautifulsoup

import re

def ngrams(input,n):

content=re.sub('\n+'," ",input)

content=re.sub(' +'," ",content)

content=bytes(content,"utf-8")

content=content.decode("ascii","ignore")

input=content.split(' ')

output=

for i in range(len(input)-n+1):

return output
html=urlopen(「

bsobj=beautifulsoup(html,「html.parser」)

content=bsobj.find(「div」,).get_text()

ngrams=ngrams(content,2)

print(ngrams)

print(「2-grams count is :」+str(len(ngrams)))

執行結果如下圖所示,結果有所改善:

但是還有一些小問題,我們繼續增加下述的規則來進行資料清理:

剔除單字元的單詞,除非這個字元是「i」或「a」

剔除維基百科的引用標記(方括號包裹的陣列,如[1])

剔除標點符號(注意:這個規則其實有點過往矯正了,後續我們會就這個問題繼續分析講解)

現在,清洗任務變得越來越長,我們把規則都移除出來,單獨建乙個函式,取名了cleaninput,**內容如下:

from urllib.request import urlopen

from bs4 import beautifulsoup

import re

import string

def cleaninput(input):

input=re.sub('\n+'," ",input)

input=re.sub('\[[0-9]*\]',"",input)

input=re.sub(' +'," ",input)

input=bytes(input,"utf-8")

input=input.decode("ascii","ignore")

cleaninput=

input=input.split(' ')

for item in input:

item=item.strip(string.punctuation)

if(len(item)>1) or (item.lower()=='a' or item.lower()=='i'):

return cleaninput
def ngrams(input,n):

input=cleaninput(input)

output=

for i in range(len(input)-n+1):

return output
html=urlopen(「

bsobj=beautifulsoup(html,「html.parser」)

content=bsobj.find(「div」,).get_text()

ngrams=ngrams(content,2)

print(ngrams)

print(「2-grams count is :」+str(len(ngrams)))

**中,引入了string,並使用了string.punctuation,目的是為了獲取到python所有的標點符號,並去除它們。如想要知道具體包含哪些符號,可在命令列執行print操作。

上述**執行結果如下圖所示,

從結果分析發現,挑選結果明顯更加乾淨了。

清洗網頁資料

ascii american standard code for information interchange美國標準資訊交換碼 只能表示128個字元 這個大家都是很熟悉的,從32是空格,然後是一堆符號,然後是48 57表示0 9,65 90是a z,97 122是a z。就是很少,也只有英文本母...

python清洗文字 用python清洗文字檔案

文章目錄txt清洗1 字串操作 2 txt的建立和讀取 3 檔案讀取以及實現 txt清洗 1 字串操作 對此,首先需要熟悉一些python基本的字串操作。在python中,字串用引號 或 來表示,並可通過類似陣列的方式進行索引,對此我們先建立乙個字串 test txt檔案csdn.com清csd.c...

python資料清洗

對於資料中缺失的值,可以有3種方法處理 1.刪除。比如餐廳的營業額,有幾天去裝修了,確實沒營業,可以刪除 2.不處理 有一些模型可以將缺失值作為一種特殊的值,可以直接建模。3.補上 均值 中位數 眾數 一般情況吧 固定值 比如工資啊,補貼啊 最近臨插補 最近的值,相鄰的,補上 下面是拉格朗日插值法 ...