我有一个包含如下数据的xml文件:
<SpeechSegment spkid="S0">
<Word dur="0.22" stime="0.44">oh</Word>
<Word dur="0.27" stime="1.67">bedankt</Word>
<Word dur="0.3" stime="2.03">voor</Word>
<Word dur="0.53" stime="2.61">deelname</Word>
</SpeechSegment>
我要做的是计算每个片段的单词数,如果有三个以上的单词,请插入另一个“SpeechSegment”标记。因此,我的首选输出如下:
<SpeechSegment spkid="S0">
<Word dur="0.22" stime="0.44">oh</Word>
<Word dur="0.27" stime="1.67">bedankt</Word>
<Word dur="0.3" stime="2.03">voor</Word>
#count is more than 3
</SpeechSegment><SpeechSegment spkid="S0">
<Word dur="0.53" stime="2.61">deelname</Word>
</SpeechSegment>
我尝试使用以下代码来实现这一点:
import xml.etree.ElementTree as ET
raw = ET.parse("Interview_short.xml")
root = raw.getroot()
for child in root:
print(child)
count_list = 0
for item in child:
print(item)
count_list = count_list + 1
if count_list > 2:
#add speech segment tag
但是我有个问题
print(child)
给我这个:
<Element 'SpeechSegment' at 0x20e3cf8>.
当我在寻找
<SpeechSegment spkid="S0">.
在项目后添加.text无效。你有什么想法吗
您可以通过调用元素上的.attrib来访问标记的属性。在您的情况下,child.attrib将返回字典{'spkid':'S0'}
现在,您可以使用python的正常方式访问字典中的键和值
希望有帮助
如果您还询问如何添加新标签,请在问题中详细说明
相关问题 更多 >
编程相关推荐