1

<context>...</context>タグ内のすべてのテキストを読み取るにはどうすればよいですか?そして、<head>...<\head>タグ内の<context \>タグはどうですか?

次のようなXMLファイルがあります。

<corpus lang="english">
    <lexelt item="coach.n">
        <instance id="1">
            <context>I'll buy a train or <head>coach</head> ticket.</context>
        </instance>
        <instance id="2">
            <context>A branch line train took us to Aubagne where a <head>coach</head> picked us up for the journey up to the camp.</context>
        </instance>
    </lexelt>
</corpus>

しかし、コードを実行して...内のXMLテキストを読み取ると、タグに到達するまでテキストを取得するだけです。

import xml.etree.ElementTree as et    
inputfile = "./coach.data"    
root = et.parse(open(inputfile)).getroot()
instances = []

for corpus in root:
    for lexelt in corpus:
      for instance in lexelt:
        instances.append(instance.text)

j=1
for i in instances:
    print "instance " + j
    print "left: " + i
    print "\n"  
    j+=1

今、私はちょうど左側を取得しています:

instance 1
left: I'll buy a train or 

instance 2
left: A branch line train took us to Aubagne where a 

出力には、コンテキストとヘッドの右側も必要です。次のようになります。

instance 1
left: I'll buy a train or 
head: coach
right:   ticket.

instance 2
left: A branch line train took us to Aubagne where a 
head: coach
right:  picked us up for the journey up to the camp.
4

2 に答える 2

3

まず第一に、あなたはあなたのコードに間違いがあります。for corpus in root必要ありません、あなたのルートはすでにcorpusです。

あなたがおそらくやろうとしていたことは:

for lexelt in root:
  for instance in lexelt:
    for context in instance:
      contexts.append(context.text)

さて、あなたの質問に関して-for context in instanceブロック内で、あなたはあなたが必要とする他の2つの文字列にアクセスすることができます:

  1. headテキストにアクセスするには、context.find('head').text
  2. 要素の右側のテキストは、 Pythonのetreeドキュメント によると次の場所にheadアクセスして読むことができます。context.find('head').tail

このtail属性を使用して、要素に関連付けられた追加のデータを保持できます。この属性は通常文字列ですが、アプリケーション固有のオブジェクトでもかまいません。要素がXMLファイルから作成されている場合、属性には、要素の終了タグの後、次のタグの前にあるテキストが含まれます。

于 2012-09-22T07:34:00.120 に答える
1

ElementTree内では、子ノードのテールプロパティを考慮する必要があります。また、あなたの場合、コーパスはルートです。

    xml.etree.ElementTreeをetとしてインポートします    
    inputfile = "./coach.data"    
    コーパス=et.parse(open(inputfile))。getroot()

    def getalltext(elem):
        elem.text +'' .join([getalltext(child)+ child.tail for child in elem])を返します。

    インスタンス=[]
    コーパスのlexeltの場合:
        たとえば、lexeltの場合:
            instance.append(getalltext(instance))


    j = 1
    インスタンスのiの場合:
        印刷"インスタンス"+j
        印刷"左:" + i
        「\n」を印刷  
        j + = 1

于 2012-09-22T08:04:47.587 に答える