2015-09-04 330 views
-1

我已經從使用BeautifulSoup的網站解析了一些文本(城市名稱)到列表中,但遇到了一個我無法克服的問題。網站上的文本元素有特殊字符,當我打印列表中的城市名被顯示爲[u'London]代替作爲特殊字符有數字和字母出現。如何在開始時擺脫「u」並將文本轉換爲最初出現在網站上的格式?Python中有特殊字符的字符串無法正確顯示

下面是代碼:

import urllib2 
from bs4 import BeautifulSoup 

address = 'https://clinicaltrials.gov/ct2/show/NCT02226120?resultsxml=true' 

page = urllib2.urlopen(address) 
soup = BeautifulSoup(page) 
locations = soup.findAll('country', text="Hungary") 
for city_tag in locations: 
    site=city_tag.parent.name 
    if site=="address": 
     desired_city=str(city_tag.findPreviousSibling('city').contents) 
     print desired_city 

,這裏是我所得到的輸出:

[u'Pecs'] 
[u'Baja'] 
[u'Balatonfured'] 
[u'Budapest'] 
[u'Budapest'] 
[u'Budapest'] 
[u'Budapest'] 
[u'Budapest'] 
[u'Budapest'] 
[u'Budapest'] 
[u'Budapest'] 
[u'Budapest'] 
[u'Budapest'] 
[u'Budapest'] 
[u'Budapest'] 
[u'Cegled'] 
[u'Debrecen'] 
[u'Eger'] 
[u'Hodmezovasarhely'] 
[u'Miskolc'] 
[u'Nagykanizsa'] 
[u'Nyiregyh\xe1za'] 
[u'Pecs'] 
[u'Sopron'] 
[u'Szeged'] 
[u'Szekesfehervar'] 
[u'Szekszard'] 
[u'Zalaegerszeg'] 

從底部[u'Nyiregyh \ xe1za']例如第七元素不正確顯示。

+0

在U前綴僅用於源代碼;如果你看到它,那是因爲你正在打印對象的表示。 [Unicode HOWTO](https://docs.python.org/2/howto/unicode.html#reading-and-writing-unicode-data)有幫助嗎?如果您不想在編碼字符上使用文檔的常規指針,您可能需要顯示一些代碼。 – dsh

回答

0

您使用str()給你,因此它可以被打印的對象轉換:

desired_city=str(city_tag.findPreviousSibling('city').contents) 
    print desired_city 

不僅你看,你問的「U」字頭,但你也看到[]''。這些標點符號是str()將這些類型的對象轉換爲文本的一部分:[]表示您有一個列表對象。該u''表明,在列表中的對象爲「文本」。 注:Python的2是在處理與字節字符相當馬虎。這種鬆散混淆使很多人感到困惑,特別是因爲有時甚至在錯誤的情況下工作,而在其他數據或環境下失敗。

既然你有一個包含unicode的對象的列表,想要打印該值:

list_of_cities = city_tag.findPreviousSibling('city').contents 
    desired_city = list_of_cities[0] 
    print desired_city 

注意,我認爲城市的名單將至少有一個元素。您顯示的示例輸出是這種方式,但也可以檢查錯誤情況。

+0

非常感謝 –