Skip to main content
 首页 » 编程设计

python之类型错误 : unsupported operand type(s) for +: 'int' and 'Element'

2024年10月24日27cloudgamer

美好的一天 每当我尝试运行下面的 python 脚本时,我都会收到错误消息。它假设给出从 XML 文件中提取的值的总和。 错误信息是: 类型错误:+ 不支持的操作数类型:'int' 和 'Element'

我已经尝试了所有选项,但错误仍然出现。我哪里错了?

源文件:

<commentinfo> 
<comments> 
<comment> 
<name>TDK</name> 
<count>5000</count> 
</comment> 
<comment> 
<name>Swats</name> 
<count>420</count> 
</comment> 
<comment> 
<name>Tandwa</name> 
<count>2000</count> 
</comment> 
</comments> 
</commentinfo> 

Python 代码:

import urllib 
import re 
import xml.etree.ElementTree as ET 
u = urllib.urlopen('file.xml') 
data = u.read() 
print 'Retrieved',len(data),'characters' 
tree = ET.fromstring(data) 
lst = tree.findall('comments/comment') 
print 'Value', len(lst) 
score=[] 
for item in lst: 
    number=int(item) 
    score.append(number) 
    total=int(sum(score)) 
print 'Sum', total 

错误信息:

Traceback (most recent call last): 
  File "test.py", line 12, in <module> 
    number=int(item) 
TypeError: int() argument must be a string or a number, not 'Element' 

请您参考如下方法:

您的问题是每个“项目”都是一个 XML 元素:

如果我修改代码如下,可以看到错误:

... 
score = [] 
for item in lst: 
    print(item) 
    number = int(item) 
    score.append(number) 
    total = int(sum(score)) 
... 

当它运行时,我们会在出现错误之前进行第一次运行。

<Element 'comment' at 0x7f9da76584a8> 

XML 元素不是“整数”或可以转换为整数的字符串。我们需要获取项目的数据,然后将其转换为整数。 “comment”元素仍然是“count”元素的父元素,因此我们需要“count”元素的text。

假设我们有树,我们可以按如下方式获取所有计数元素:

lst = tree.findall('comments/comment/count') 

然后我们可以使用元素文本中的 int() 内置函数获取值:

# this is a generator expression, it tells the code how to run but doesn't do it yet 
scores = (int(i.text) for i in lst) 

然后,我们可以评估总数:

total = sum(scores) 

总代码(加载后打开文件作为数据读取)如下:

print('Retrieved', len(data), 'characters') 
 
tree = ET.fromstring(data) 
lst = tree.findall('comments/comment/count') 
print('Value', len(lst)) 
 
scores = (int(i.text) for i in lst) 
total = sum(scores) 
print('Sum', total) 

我们得到的结果是:

Retrieved 230 characters 
Value 3 
Sum 7420