2012-10-13 51 views
0

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

列表例如:

[<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 

感谢, 弗兰克

+0

你以前的问题表明你使用'BeautifulSoup()'应该自动处理字符编码。你如何得到''? (提供一些代码) – jfs

+0

你是对的J.F.这里是我玩的代码(在上面发布)。 –

回答

3

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

+0

网站编码表示UTF-8 –

+0

然后取每个字符串并使用'encoded_string.decode('utf-8')' –

+1

对我来说不幸的是,这个回答不起作用,因为网站/说/ UTF-8,但包含垃圾字符全部都一样。 – davenpcj

0

你有尝试吗?

这可能有效。

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

输出:

10115 
4635 (46%) 
5276 (52%) 

取决于它是如何不变(如果它总是只有一个点的一个),可能有更好的方法去(从\更换任何东西的空间带有空白字符)。

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. 
+0

感谢您的解码帮助。 –

+0

这工作对我来说,网站返回垃圾字符以外的声明的编码 – davenpcj

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\xa' 

请注意,文本是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%)']