【问题标题】:String with special characters in Python do not appear correctlyPython 中带有特殊字符的字符串无法正确显示
【发布时间】:2015-09-04 17:57:36
【问题描述】:

我使用 BeautifulSoup 将网站上的一些文本(城市名称)解析为列表,但遇到了一个我无法克服的问题。网站上的文本元素有特殊字符,当我打印列表时,城市名称显示为 [u'London],而不是特殊字符,出现了数字和字母。如何去掉开头的“u”,将文本转换为网站上最初显示的格式?

代码如下:

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']

例如,底部的第 7 个元素 [u'Nyiregyh\xe1za'] 显示不正确。

【问题讨论】:

  • u 前缀仅用于源代码;如果您看到它,那是因为您正在打印对象的表示。 Unicode HOWTO 有帮助吗?如果您想要的不仅仅是指向有关编码字符的文档的一般指针,您可能需要显示一些代码。

标签: python unicode beautifulsoup special-characters


【解决方案1】:

您使用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

请注意,我假设城市列表至少包含一个元素。您显示的示例输出是这样的,但也可以检查错误情况。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-21
    • 2017-06-25
    • 1970-01-01
    • 2014-02-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多