第一天的工作:找到數據源,數據下載,數據處理。 數據源:"http://webhelp.esri.com/arcgisserver/9.3/java/geodatabases/definition_frame.htm"。 數據下載:右擊網頁另存為。 數據處理:bs4 + 對比觀察 + chrome檢 ...
第一天的工作:找到數據源,數據下載,數據處理。
數據源:"http://webhelp.esri.com/arcgisserver/9.3/java/geodatabases/definition_frame.htm"。
數據下載:右擊網頁另存為。
數據處理:bs4 + 對比觀察 + chrome檢查元素 + 寫function寫方法
一、bs4部分
from bs4 import BeautifulSoup soup = BeautifulSoup(open('GIS_dictionary.html','r',encoding='UTF-8'),features="lxml") #tag標簽 GlossaryTerm_list = soup.find_all(attrs={'class':'GlossaryTerm'})#完整,1729個 Definition_list = soup.find_all(attrs={'class':'Definition'})#缺<ol>
二、對比觀察 + 檢查元素
在準備GlossaryTerm和Definition的一一對應時發現二者的數量對不上。觀察分析後確定是網站的前端代碼對不同形式的Definition有不同的處理方法:對有多項釋義的辭彙使用了<ol>有序列表,它不能直接被bs4的屬性查找選擇到。
三、寫方法
第一塊:因為片語和解釋在同一前端代碼段內,故使用".text"和".a.attrs['name']"完成第一部分的對應。
''' 完成Definition_list中已有的1610個解釋的文本獲取和詞語對應 ''' defList = [] for i in Definition_list: defi = i.text.strip('\n')#修飾definition word = i.a.attrs['name'].replace('_',' ')#修飾glossary defList.append([defi,word]) #抓取所有解釋和詞語在小列表,再存入大列表 if (i.text==''): #確保沒有definition為空 print(i.a.attrs['name']) #defList示例[["defi",'word'],["",''],["",''],["",'']...]
第二塊:定義函數func_n(),清洗<ol>標簽內的數據。其中使用了通過中間媒介list修改string的技巧和if篩查的方法。最後對應片語和相應的解釋,完成項目的數據準備工作。明日計劃:資料庫。
''' <ol>標簽,將defList補充完整,從Ctrl+F得到共有119個<ol>標簽 "1610+119=1729",成功!1729 == len(GlossaryTerm_list) ''' #定義函數func_n #格式化<ol>的definition:首位加"1.";將多個連續的"\n"收為一個;在"\n"後添加"2."等序號 def func_n(txt): lstTxt = list(txt) #因為不能直接修改string,故將其打碎為list進行操作 n = len(lstTxt) newlstTxt = ["1."] #添加首位的"1." count = 2 for i in range(n-1): if lstTxt[i]=='\n' and lstTxt[i]!=lstTxt[i+1] and lstTxt[i+1]!=' ': #保留單獨的"\n",在其後添加序號;排除'\n'+' '的組合 newlstTxt.append('\n') newlstTxt.append(str(count)) newlstTxt.append('.') count += 1 if lstTxt[i]!='\n' and lstTxt[i]!=lstTxt[i+1] and lstTxt[i]!='\t': #放棄連續多個的"\n"、放棄所有的'\t' newlstTxt.append(lstTxt[i]) newlstTxt.append(lstTxt[-1]) #添加for迴圈里沒有的最後一位 strTxt = ''.join(newlstTxt) #''.join()函數將list變為string return strTxt #實操 ol_list = soup.find_all('ol') for j in ol_list: defi_ol = j.text.strip('\n') defi_ol = func_n(defi_ol) word_ol = j.a.attrs['name'].replace('_',' ') defList.append([defi_ol,word_ol])
詞典數據效果: