我在名为" sample.xml"
的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>
我想加载xml数据,所以我可以像这样:
raw = '''<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>'''
from xml.etree import ElementTree as ET
root = ET.fromstring(raw)
result = [word.text for word in root.findall('Word')]
print result
但问题是我似乎无法从xml文件加载数据。我试着这样做:
import xml.etree.ElementTree as ET
raw2 = ET.parse('Interview_short.xml')
但是这不起作用:
from xml.etree import ElementTree as ET
root = ET.fromstring(raw2)
result = [word.text for word in root.findall('Word')]
print result
答案 0 :(得分:0)
您在parse(**Interview_short.xml**)
中使用了不同的文件。您说您的数据位于文件**sample.xml**
中
以下工作正常:
import xml.etree.ElementTree as ET
raw2 = ET.parse('sample.xml')
print([word.text for word in raw2.findall('Word')])
答案 1 :(得分:0)
以下xml.etree.elementTree soup = BeautifulSoup(...)
items = soup.find_all('a')
for item in items:
if item.parent.name != u'p':
item.wrap(soup.new_tag('p'))
和ET.parse
的文档不能一起用于获取xml的根元素。
要么在ET.fromstring
返回的树上调用raw2.getroot()
,要么将整个xml-string提供给ET.parse
方法,例如使用open。
小例子:
ET.fromstring