特定のタグ(<question>
)が埋め込まれたxml文書を解析しているので、閉じた後にテキストがあるかどうかを確認する必要があります終了親タグ</Turn>
まで、</question>
タグを使用します。問題は、</question>
と</Turn>
の間に他のタグがある可能性があります。改行や空白、さらにはこれらのすべてであっても、質問の尾だけでは不十分です。ここでlxml要素の後ろにテキストがあるかどうかチェックする(tailだけではない)
は、私が働いているxmlファイルの一部のいくつかの例です:
<root>
<Turn speaker="spk2" startTime="5121.203" endTime="5136.265">
<question startline="8321" endline="8326">
<Sync time="5121.203"/>
some text
<Sync time="5126.531"/>
<Sync time="5127.662"/>
other text?</question><question startline="8326" endline="8326">
here are some other words?
</question>
<Sync time="5128.514"/>
THIS IS SOME TEXT I WANT TO GET <anothertag att="2"/> SOME OTHER TEXT
<annoyingtag att="blah"/>
AND THIS TOO
</Turn>
<Turn>
<question>
this is a question?
</question>
this is not, I want to get this text.
</Turn>
<Turn>
There could be a turn with no question here.
</Turn>
<Turn>
<question>
and then another with a question?
</question>
followed by
<Sync/>
other text
but also
<Event/>
other tags
<Who/>
and I want to get all this text.
</Turn>
</root>
私はpythonでlxmlのを使用してXMLを処理しています。私は</question>
と</Turn>
の間にいくつかのテキストがあるかどうかを確認したい場合は、私のようなループ処理の質問のためにすでに午前:
Turns = rootnode.findall(".//Turn")
for Turn in Turns:
questions = Turn.findall(".//question")
for question in question:
if question == questions[-1]:
#This is where I will insert the code trying to find if there is some text following the question tag.
私は両方question.tail()
この他に尾を取得しようとしましたメソッドquestion.xpath("//text()")[1]
ですが、どちらの場合も、最後の</question>
と</Turn>
の間のテキストはすべて表示されません。
正規表現を使って生ファイルでもやってみましたが、2つの終了タグの間に多くのことがあるので、ネストされた数量子と致命的なバックトラッキングの問題がありました。
感謝を。問題は、Syncタグが常に存在しないことです。また、「」や「」のように、Syncの代わりに他のタグを使用することもできます。 –
もっと複雑な例を追加した場合、それが役に立ちます。最後のxpathは何があっても機能しますが、すべての可能性についてはわかりません。 –
さらに、と、の間のテキストを探しているときに、私はすでに ' 'タグを特定しています。ターンの質問をループするしたがって、私は 'question == questions [-1]:'で最後の質問を特定しようと考えていましたが、これがXPathを適用すべきところです。私はこの式を試しましたが、何も得られません: 'print(question.xpath(" following :: */following :: text() "))' –