Python BeautifulSoup字符串浮动

时间:2014-03-22 13:47:05

标签: python unicode beautifulsoup

我从在线网页下载了xml格式的数据集。我使用python的beautifulsoup库提取了values标签。这给了我unicode值。

graphs = soup.graphs
c = 0
for q in graphs:
    name = q['title']
    data = {}

    for r in graphs.contents[c]:
        print float(str(unicode(r.string)))
        data[r['xid']] = unicode(r.string)
    c = c + 1

    result[name] = [data[k] for k in key]

来源为http://charts.realclearpolitics.com/charts/1171.xml

我想制作r.string float type

所以我做了

print float(str(unicode(r.string)))
print float(unicode(r.string))

但我遇到了这个错误的

File "<ipython-input-142-cf14a8845443>", line 73
    print float(unicode(r.string)))
                              ^
SyntaxError: invalid syntax

我该怎么办?

2 个答案:

答案 0 :(得分:0)

语法错误是由于括号不平衡(从右侧删除一个)。 r.string可能是None,因此TypeError

答案 1 :(得分:0)

第一个错误是圆括号不平衡。

print float(str(unicode(r.string))))
                                   ^ 4th here

第二个错误,在进行操作之前检查值是否为None。否则你会收到错误ValueError: could not convert string to float: None

所以修复将是:

if(r.string != None):
    print float(str(unicode(r.string)))