【问题标题】:Python BeautifulSoup string to floatPython BeautifulSoup 字符串浮动
【发布时间】:2025-12-27 18:30:06
【问题描述】:

我从在线网页下载了一个 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 浮动类型

原来如此

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

我该怎么办?

【问题讨论】:

  • float(r.string) 也有 Err TypeError: float() argument must be a string or a number
  • 这似乎是题外话,因为它是由不可重现的印刷错误引起的。
  • 那么,如何将类型 None 更改为任何类型??

标签: python unicode beautifulsoup


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

    【讨论】: