Python でワード クラウド プログラムの作成に取り組んでいますが、単語の置換機能に行き詰まっています。HTMLファイル内の一連の数字を順序付きリストの単語に置き換えようとしています(したがって、文字列で作業しています)。したがって、000 はリストの最初の単語に、001 は 2 番目の単語に、というように置き換えられます。
以下のこのメソッドは、比較的単純な文字列を移動するときに機能します。
def textReplace():
text = '000 this is 001 some 002 text 003 '
word = ['foo', 'bar', 'that', 'these']
for a in word:
for y, w in enumerate(text):
x = "00"+str(y)
text = text.replace(x, a)
print text
私はhtmlファイルを処理しています(ファイルの一部を以下の文字列に入れます)、000、001、002などの各インスタンスをリスト内の連続するアイテムに置き換える代わりに、すべての数字を最初のアイテムに置き換えます。このメソッドが上記の文字列では機能するのに、下の文字列では機能しないのはなぜですか。どんな助けでも大歓迎です。ありがとう!
def htmlReplace():
text = '<p><span class="newStyle0" style="left: 291px; top: 258px">000</span></p> <p><span class="newStyle1" style="left: 85px; top: 200px">001</span></p> <p><span class="newStyle2" style="left: 580px; top: 400px; width: 167px; height: 97px">002</span></p> <p><span class="newStyle3" style="left: 375px; top: 165px">003</span></p>'
word = ['foo', 'bar', 'that', 'these']
for a in word:
for y, w in enumerate(text):
x = "00"+str(y)
text = text.replace(x, a)
print text