2015-09-04 335 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

非常感谢 –