2012-01-30 44 views
-1

今天早上,我花了幾個令人沮喪的時間,試圖處理來自刮網頁的字符串。我似乎無法得到一種降低提取的字符串的一致方式,因此我可以檢查關鍵字 - 並將其推動我轉彎。BeautifulSoupTag,字符串和UnicodeEncodeError不是很漂亮

下面是一個代碼片段,從一個DOM元素檢索文字:

temp = i.find('div', 'foobar').find('div') 
if temp is not None and temp.contents is not None: 
    temp2 = whitespace.sub(' ', temp.contents[0]) 
    content = str(temp2) 

UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 150: ordinal not in range(128)

我也嘗試下面的語句 - 其中沒有工作;即,它們導致了同樣的錯誤被拋出:

content = (str(temp2)).decode('utf-8').lower() 
content = str(temp2.decode('utf-8')).lower() 

有誰知道如何包含在BeautifulSoupTag內成小寫ASCII德文本轉換,所以我可能會進行的關鍵字不區分大小寫的搜索?

+2

嘗試在這裏找到了答案:[文件](http://www.crummy.com/software/BeautifulSoup/documentation.html#Beautiful湯給你的Unicode,該死的) – methyl 2012-01-30 12:36:06

+0

你能只需使用'unicode(temp2)'? – 2012-01-30 12:45:36

+0

閱讀我的答案,你已經接受[你幾乎相同的問題](http://stackoverflow.com/q/9012607/4279) – jfs 2012-01-30 14:30:39

回答

2

你可能想要ASCII碼,但是你需要Unicode,而且很有可能你已經擁有它了。 XML解析器返回unicode對象。

首先做print type(temp2) ...應該是unicode除非發生了不幸的事情,比如說可能是whitespace.sub() thingy;那是什麼?

如果你想多個空白字符標準化成一個單一的空間,做

temp2 = u' '.join(temp.contents[0].split())

這將使那個討厭的U '\ XA0' 消失,becase的這是一個空白(NO-BREAK SPACE)。

然後嘗試content = temp2.lower()

相關問題