8

Pythonで次の置換を実現しようとしています。すべての html タグを {n} に置き換え、[tag, {n}] のハッシュを作成
元の文字列 -> " <h>This is a string. </H><P>This is another part. </P>"置換された
テキスト -> "{0} This is a string. { 1}{2} これは別の部分です。{3}"

これが私のコードです。置換を開始しましたが、各オカレンスを連続して置換する最良の方法、つまり {0}、{1} などを見つけることができないため、置換ロジックに行き詰まっています。

import re
text = "<h> This is a string. </H><p> This is another part. </P>"

num_mat = re.findall(r"(?:<(\/*)[a-zA-Z0-9]+>)",text)
print(str(len(num_mat)))

reg = re.compile(r"(?:<(\/*)[a-zA-Z0-9]+>)",re.VERBOSE)

phctr = 0
#for phctr in num_mat:
#    phtxt = "{" + str(phctr) + "}"
phtxt = "{" + str(phctr) + "}"
newtext = re.sub(reg,phtxt,text)

print(newtext)

誰かがこれを達成するためのより良い方法を手伝ってもらえますか? ありがとうございました!

4

1 に答える 1

7
import re
import itertools as it

text = "<h> This is a string. </H><p> This is another part. </P>"

cnt = it.count()
print re.sub(r"</?\w+>", lambda x: '{{{}}}'.format(next(cnt)), text)

版画

{0} This is a string. {1}{2} This is another part. {3}

単純なタグのみで機能します (タグに属性/スペースはありません)。拡張タグの場合、正規表現を適応させる必要があります。

また、再初期cnt = it.count()化しないと、番号付けが続行されます。

マッピング dict を取得するための更新:

import re
import itertools as it

text = "<h> This is a string. </H><p> This is another part. </P>"

cnt = it.count()
d = {}
def replace(tag, d, cnt):
    if tag not in d:
        d[tag] = '{{{}}}'.format(next(cnt))
    return d[tag]
print re.sub(r"(</?\w+>)", lambda x: replace(x.group(1), d, cnt), text)
print d

プリント:

{0} This is a string. {1}{2} This is another part. {3}
{'</P>': '{3}', '<h>': '{0}', '<p>': '{2}', '</H>': '{1}'}
于 2012-11-29T09:42:58.193 に答える