py3.6 編譯器pycharm
在這本書第七章數據清洗一節中,作者採集wikipeidia上的文本,並用2grams方法對數據進行處理,具體的函數如下:
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"):
cleanInput.append(item)
return cleanInput
def ngrams(input,n):
input=cleaninput(input)
output=[]
for i in range(len(input)-n+1):
output.append(input[i:i+n])
return output
html=urlopen("http://en.wikipedia.org/wiki/Python_(programming_language)")
bsObj=BeautifulSoup(html,'lxml')
content=bsObj.find("div",{"id":"mw-content-text"}).get_text()
ngrams=ngrams(content,2)
print(ngrams)
print("2-grams count is:"+str(len(ngrams)))
該函數最後的輸出結果應該爲一個列表list,如下:
[['Python', 'Paradigm'], ['Paradigm', 'Object-oriented'], ['Object-oriented',
'imperative'], ['imperative', 'functional'], ['functional', 'procedural'], ......]
之後爲了將該列表中重複的元素合併並統計詞頻,作者將函數修改爲:
.....
from collections import OrderedDict
........
ngrams=ngrams(content,2)
ngrams=OrderedDict(sorted(ngrams.items(),key=lambda t:t[1],reverse=True))
print(ngrams)
print("2-grams count is:"+str(len(ngrams)))
這裏由於ngrams爲一個列表list,因此編譯器報錯顯示’list‘ object has no attribute ‘items’。
在這裏將書上的代碼修改爲如下:
......
from collections import OrderedDict
.........
ngrams=ngrams(content,2)
ngrams_dict={}
for i in ngrams:
n=ngrams.count(i)
i=str(i)#將list i 轉變爲一個字符串用作健key,並利用了python字典的key具有唯一性的屬性
ngrams_dict[i]=n
ngrams=OrderedDict(sorted(ngrams_dict.items(),key=lambda t:t[1],reverse=True))
print(ngrams)
print("2-grams count is:"+str(len(ngrams)))
之後函數便可輸出與書上相近的結果:
OrderedDict([("['Python', 'Software']", 37), ("['Software', 'Foundation']", 37),
("['of', 'the']", 34), ("['Foundation', 'Retrieved']", 30), ("['of', 'Python']", 28), .....]
在python網絡數據採集一書中,對作者未寫完的函數進行修改,並基於此發現python編程中的問題。
1)、列表元素不能作爲字典的健,原因在於其不能夠提供唯一的哈希值,詳情見鏈接:Why list can't be a dictionary keys?
2)、集合(set)中不能夠添加list作爲元素,原因同上。
例如:
a=set([1,2,2])
輸出結果爲:a={1,2}。
但是代碼
a=set([[1,2,2],[1,2,2]])
則會報錯,顯示unhashable type: 'list',因此與set有關的方法add等也不能夠添加list作爲元素,若要求像類似書中的列表作爲鍵值使用一樣,則只能將其轉換成string類型使用。
3)、python中統計列表中元素出現個數(要求value-n對應)的方法:
-
方法一:
List = [1,2,3,4,5,3,2,1,4,5,6,4,2,3,4,6,2,2]
List_set = set(List) #List_set是另外一個列表,裏面的內容是List裏面的無重複 項
for item in List_set:
print("the %d has found %d" %(item,List.count(item))) -
方法二:(利用字典的特性來實現)
List=[1,2,3,4,5,3,2,1,4,5,6,4,2,3,4,6,2,2]
a = {}
for i in List:
if List.count(i)>1:
a[i] = List.count(i)
a = sorted(a.items(), key=lambda item:item[0])
print (a) -
方法三:
from collections import Counter
List=[1,2,3,4,5,3,2,1,4,5,6,4,2,3,4,6,2,2]
Counter(list)
注意該方法中Counter實際上生成了一個字典,因此如果List本身是一個帶有List作爲元素的複合的列表,這種方法不能夠使用