Python列表返回一个unicode列表

时间:2016-01-07 01:01:52

标签: python unicode

我似乎无法弄清楚为什么我会收到以Unicode格式返回的列表?在下面的代码块中。我尝试过打印类型(data_new)并返回unicode列表,即使我试图拉出ASCII列表。

任何指导都会有所帮助。

<小时/> <小时/>

from BeautifulSoup import BeautifulSoup
import re
import urllib

new_data = list()
sum = 0
url = 'http://python-data.dr-chuck.net/comments_42.html'
soupy = urllib.urlopen(url).read()
soup = BeautifulSoup(soupy)
    for p in soup:
p = re.compile('<span class="">(.*?)\</span>', re.IGNORECASE|re.DOTALL)
p = soup.findAll('span',{'class':'comments'})
for row in p:
    text = ''.join(row.findAll(text=True))
    data = text.strip()
    new_data = data
    for i in new_data:
       sum + i
       print type(sum)
    else:
       print 'Your a terrible programmer: in the loop'             
if sum > 0:
    print 'Sum of numbers in file:', sum
else:
    print 'Your a terrible programmer: at the end'

2 个答案:

答案 0 :(得分:4)

从这里: http://www.crummy.com/software/BeautifulSoup/

  

Beautiful Soup会自动将传入的文档转换为Unicode,将传出的文档转换为UTF-8。

因此,要将它从unicode转换为str,请使用str()。但我想你需要int()才能用数字做数学。

一个更清洁的例子:

from BeautifulSoup import BeautifulSoup
import urllib

url = 'http://python-data.dr-chuck.net/comments_42.html'
soupy = urllib.urlopen(url).read()
soup = BeautifulSoup(soupy)
rows = soup.findAll('span')
for row in rows:
    text = ''.join(row.findAll(text=True)) #<--- Here the text is unicode (1)
    data = int(text) #<--- to do math convert it to int (2)
    print data, type(data)

(1)row.findAll(text=True)返回一个unicode字符串列表。然后,您将此列表的元素加入到字符串中:''.join(your_list)。 因此,您有一个预期的unicode字符串。

(2)有时人们会int(s.strip()),但不需要剥离,因为int()会忽略前导和尾随空格。

答案 1 :(得分:0)

这可能与BeautifulSoup将类 NavigableString 用于搜索中返回的任何字符串的事实有关。该类与其他一些属性实际上是unicode。

http://www.crummy.com/software/BeautifulSoup/bs4/doc/#navigablestring

您始终可以使用 str()来投射结果,但在您的情况下,因为您要加起来,您可能需要 int()值为此。