私は初心者のプログラマーであり、このおそらく些細な問題について何か助けていただければ幸いです。次の構造を含む .xml ファイルがあります。
<norm builddate="20120625150106" doknr="BJNR000020963BJNE000401308">
<metadaten>
<jurabk>BUrlG</jurabk>
<enbez>§ 3</enbez>
<titel format="parat">sometitle</titel>
</metadaten>
<textdaten>
<text format="XML">
<Content>
<P>(1) sometext</P>
<P>(2) anothertext</P>
</Content>
</text>
<fussnoten/>
</textdaten>
</norm>
ここで、各 "P" コンテンツに、タグ "enbez" + "P" (somenumber) + "jurabk" の文字列コンテンツを追加します。この例では、§ 3 (1) BUrlG. 次に、何らかのフォーマットを適用して、§ 3 Abs にします。1 バーグ。
特定の「enbez」と特定の「P」タグの場合の動作するサンプル コードを取得できました。しかし、ドキュメント全体に対してこの手順を自動的に実行できるようにしたいのですが、各「enbez」で各「P」タグを取得し、正しい段落に追加機能を適用するための反復子を正しく記述できませんでした。また、私は道のすべてのステップを可能な限り不器用に書いています。何かより良い方法があれば、アドバイスをいただければ幸いです!
サンプルコード:
import string
import re
from urllib import urlopen
from bs4 import BeautifulSoup
xmlfile = urlopen('burlg.xml').read()
soup = BeautifulSoup(xmlfile)
# Find a specific enbez; the norm parent always contains only one
enbez = soup.findAll("enbez")
enbezspecial = enbez[3]
#find the norm parent
norm = enbezspecial.find_parent("norm")
#find all p's belonging to the norm parent
p = norm.findAll("p")
pspecial = p[1]
#Get the number, remove the brackets and add a whitespace
regex = re.compile('\(\d\)')
result = regex.match(pspecial.string)
resultstring = result.group()
resultstring1 = resultstring.replace("(","")
resultstring2 = resultstring1.replace(")","")
resultstring3 = " " + resultstring2
#find the shorttitle; is the same for the whole document
jurabk = soup.find("jurabk")
#add some output formatting
enbezprint = enbezspecial.text
paraprint = " Abs."+resultstring3
jurabkprint = " "+jurabk.text
appendix = "["+enbezprint+paraprint+jurabkprint+"]"
p[1].append(appendix)
print p[1]