Python转换非标准字符

时间:2012-10-13 23:50:58

标签: python utf-8 replace ascii strip

我有一个列表,我从包含一些非标准字符的网页中提取。

列表示例:

[<td class="td-number-nowidth"> 10 115 </td>, <td class="td-number-nowidth"> 4 635 (46%) </td>, <td class="td-number-nowidth"> 5 276 (52%) </td>, ...]
戴着帽子的A应该是逗号。有人可以建议如何转换或替换这些,以便我可以得到值10115,如列表中的第一个值?

源代码:

from urllib import urlopen
from bs4 import BeautifulSoup
import re, string
content = urlopen('http://www.worldoftanks.com/community/accounts/1000395103-FrankenTank').read()
soup = BeautifulSoup(content)

BattleStats = soup.find_all('td', 'td-number-nowidth')
print BattleStats

谢谢, 弗兰克

4 个答案:

答案 0 :(得分:3)

网站是否在Content-Encoding标题中说明编码?你必须得到它,并使用.decode方法解码列表中的那些字符串。它就像encoded_string。decode(“encoding”)。 encoding可以是任何内容,utf-8就是其中之一。

答案 1 :(得分:2)

您可以将.decode方法与errors='ignore'参数一起使用。

>>> s = '[ 10Â 115 , 4Â 635 (46%) , 5Â 276 (52%) , ...]'
>>> s.decode('ascii', errors='ignore')
u'[ 10 115 , 4 635 (46%) , 5 276 (52%) , ...]'

这里是help(''.decode)

decode(...)
    S.decode([encoding[,errors]]) -> object

    Decodes S using the codec registered for encoding. encoding defaults
    to the default encoding. errors may be given to set a different error
    handling scheme. Default is 'strict' meaning that encoding errors raise
    a UnicodeDecodeError. Other possible values are 'ignore' and 'replace'
    as well as any other name registered with codecs.register_error that is
    able to handle UnicodeDecodeErrors.

答案 2 :(得分:0)

你有尝试吗?

这可能有用。

a =  ['10Â 115', '4Â 635 (46%)', '5Â 276 (52%)']
for b in a:
    b.replace("\xc3\x82 ", '')

输出:

10115
4635 (46%)
5276 (52%)

取决于它的常数(如果它始终只是带点的a),可能有更好的方法(从\替换任何空格中的空格)。

答案 3 :(得分:0)

BeautifulSoup handles character encodings automatically。问题是打印到控制台似乎不支持某些Unicode字符。在这种情况下,它是'NO-BREAK SPACE' (U+00A0)

>>> L = soup.find_all('td', 'td-number-nowidth')
>>> L[0]
<td class="td-number-nowidth"> 10 123 </td>
>>> L[0].get_text()
u' 10\xa0123 '

请注意,文本是Unicode。检查print u'<\u00a0>'是否适用于您的情况。

您可以在运行脚本之前通过更改PYTHONIOENCODING环境变量来操纵使用的输出编码。因此,您可以将输出重定向到指定utf-8编码的文件,并在控制台中使用ascii:backslashreplace值进行调试运行,而无需更改脚本。 bash中的示例:

$ python -c 'print u"<\u00a0>"' # use default encoding
< >
$ PYTHONIOENCODING=ascii:backslashreplace python -c 'print u"<\u00a0>"'
<\xa0>
$ PYTHONIOENCODING=utf-8 python -c 'print u"<\u00a0>"' > output.txt

要打印相应的数字,您可以拆分不可破坏的空间以便以后处理项目:

>>> [td.get_text().split(u'\u00a0')
...  for td in soup.find_all('td', 'td-number-nowidth')]
[[u' 10', u'115 '], [u' 4', '635 (46%) '], [u' 5', u'276 (52%) ']]

或者你可以用逗号替换它:

>>> [td.get_text().replace(u'\u00a0', ', ').encode('ascii').strip()
...  for td in soup.find_all('td', 'td-number-nowidth')]
['10, 115', '4, 635 (46%)', '5, 276 (52%)']