2017-10-18 104 views
0

编辑字符串列表:解析XML作为蟒蛇

-<corpus lang="en" id="subtask2-heterographic"> 


-<text id="het_1"> 

    <word id="het_1_1">'</word> 

    <word id="het_1_2">'</word> 

    <word id="het_1_3">I</word> 

    <word id="het_1_4">'</word> 

    <word id="het_1_5">m</word> 

    <word id="het_1_6">halfway</word> 

    <word id="het_1_7">up</word> 

    <word id="het_1_8">a</word> 

    <word id="het_1_9">mountain</word> 

    <word id="het_1_10">,</word> 

    <word id="het_1_11">'</word> 

    <word id="het_1_12">'</word> 

    <word id="het_1_13">Tom</word> 

    <word id="het_1_14">alleged</word> 

    <word id="het_1_15">.</word> 

</text> 


-<text id="het_2"> 

    <word id="het_2_1">I</word> 

    <word id="het_2_2">'</word> 

    <word id="het_2_3">d</word> 

    <word id="het_2_4">like</word> 

    <word id="het_2_5">to</word> 

    <word id="het_2_6">be</word> 

    <word id="het_2_7">a</word> 

    <word id="het_2_8">Chinese</word> 

    <word id="het_2_9">laborer</word> 

    <word id="het_2_10">,</word> 

    <word id="het_2_11">said</word> 

    <word id="het_2_12">Tom</word> 

    <word id="het_2_13">coolly</word> 

    <word id="het_2_14">.</word> 

</text> 
</corpus> 

我解析Python的XML文件,并得到我想要的文本XML文件。每个文本标签都代表XML文件中的一个句子,并且我希望将每个句子作为单独的列表元素放入列表中。

tree = ET.ElementTree(file='subtask2-heterographic-test.xml') 
root = tree.getroot() 

lst = [] 

for elem in root: 
    for w in elem: 
     lst.append(w.text) 

>> ["'", "'", 'I', "'", 'm', 'halfway', 'up', 'a', 'mountain', ',', "'", "'", 'Tom', 'alleged', '.', 'I', "'", 'd', 'like', 'to', 'be', 'a', 'Chinese', 'laborer', ',', 'said', 'Tom', 'coolly', '.', 'Dentists', ...] 

这只是给出XML文件中的所有单词而不分隔句子。 我怎样才能修复它把每个句子作为一个字符串列表放入列表中?

最终预期输出:

>> [["'", "'", 'I', "'", 'm', 'halfway', 'up', 'a', 'mountain', ',', "'", "'", 'Tom', 'alleged', '.'] , ['I', "'", 'd', 'like', 'to', 'be', 'a', 'Chinese', 'laborer', ',', 'said', 'Tom', 'coolly', '.'], ['Dentists', ...] ] 
+0

在开始 – RomanPerekhrest

+0

@RomanPerekhrest对不起发表您的XML片段。编辑。 – user6792790

+0

好的,我们得到了输入。现在,请发布最终的预期产出 – RomanPerekhrest

回答

1

你必须为每个句子一个新的列表:

sentences = [] 
for elem in root: 
    sentence = [] 
    for w in elem: 
     sentence.append(w.text) 
    sentences.append(sentence)