2017-02-22 9 views
0

body要素の下に含まれるすべての生テキストを抽出する目的で、いくつかの大きなxmlファイルを解析しています。私はテキストがどのサブ要素で発生するのか - 私はすべてのテキストを連結しています。入れ子要素が存在する場合、lxmlはすべてのテキストを抽出できません。

# find all instances of `body` 
result = [] 
for body in tree.findall('.//{*}body'): 
    # iterate recursively over all sub-elemetns of `body` 
    for node in body.iter('*'): 
     # append any text if it exists 
     if node.text: 
      # handle the text 
      result.append(node.text.strip()) 
print(' '.join(result)) 

かなり簡単、と私ははそれが働いていたをと思ったが、私は私が「は失敗していますいくつかのケースを見つけた:

私はこれを達成するために使用しているコードの該当ビットがありますどのように回避するか分からない。ここでは、XMLファイルから抽出された最小限の例です:

<cja:body> 
    <ce:sections xmlns:ce=".../xml/common/schema"> 
    <ce:para view="all">For scyptolin A or B the IC 
       <ce:inf loc="post">50</ce:inf> was erroneously calculated at 3.1 μg/ml. The correct IC 
       <ce:inf loc="post">50</ce:inf> was determined at 0.16 μg/ml for both scyptolins. 
      </ce:para> 
    </ce:sections> 
</cja:body> 

私はこのXMLに上記のコードブロックを実行した場合、出力は次のとおりです。

For scyptolin A or B the IC 50 50 

ので問題は、paraノードに対して、node.textですは、の前に発生するテキストを取得するように見えます。のネストされたinf要素です。ネストされた要素の前に出現するだけでなく、すべてのテキストをどのように抽出するのですか?明確にするために、ここで所望の出力は次のようになります。

For scyptolin A or B the IC 50 was erroneously calculated at 3.1 μg/ml. The correct IC 50 was determined at 0.16 μg/ml for both scyptolins. 
+0

ああ、私は '.tail'属性を探しているようです。[この質問](https://stackoverflow.com/questions/16701546/how-to-extract-text-in-nested-xml) -after-closing-of-one-tag-in-python-using-xml-e) – moustachio

答えて

0

が、これはthis questionに非常によく似ているが判明し、私は完全を期すため、ここでお答えします。

それは私がそれを以下のテキストを取得するためにinf要素の.tail属性を使用する必要が判明した(驚きだった...私は、テキストはまだpara要素の属性だろうと思いました)。したがって、固定コードは次のようになります。所望に応じて

For scyptolin A or B the IC 50 was erroneously calculated at 3.1 μg/ml. The correct IC 50 was determined at 0.16 μg/ml for both scyptolins. 

をもたらす

result = [] 
for body in tree.findall('.//{*}body'): 
    # iterate recursively over all sub-elemetns of `body` 
    for node in body.iter('*'): 
     # append any text if it exists 
     if node.text: 
      result.append(node.text.strip()) 
     # NEW! add `node.tail` if present: 
     if node.tail: 
      result.append(node.tail.strip()) 
print(' '.join(result)) 

関連する問題