0

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            
4

2 に答える 2

2

そのようなものは、(HTML以外の場合)次のように書く方がはるかに優れています:

>>> text = '000 this is 001 some 002 text 003'
>>> word = ['foo', 'bar', 'that', 'these']
>>> word_list = iter(word)
>>> import re
>>> re.sub(r'\d+', lambda L: next(word_list), text)
'foo this is bar some that text these'
于 2012-12-09T14:56:24.957 に答える
0

残念ながら、この種の問題はTemplate Enginesの良い候補であるため、あなたのアプローチは完全に間違っています。

利用可能なテンプレートエンジンの数を試すか、目的にかなうJinja2を提案できます。これはJinja2の例です

>>> text = """
{% for style in styles %}
<p><span class="newStyle{{ style.styleno }}"
{% for orin in style.orin %}
style="{{ orin.orin }}: {{ orin.attrib }}px
{% endfor %}
">{{ style.val }}</span></p>
{% endfor %}
"""
>>> styles = [{'no':1,
           "orin":[{"orin":"left", "attrib":291},
               {"orin":"top", "attrib":258}],
           "val":"000"},
           {'no':2,
        "orin":[{"orin":"left", "attrib":100},
            {"orin":"top", "attrib":222},
            {"orin":"height", "attrib":222},
            {"orin":"width", "attrib":222}],
        "val":"001"}]
>>> template = Template(text)
>>> template.render(styles = styles)
u'\n\n<p><span class="newStyle"\n\nstyle="left: 291px\n\nstyle="top: 258px\n\n">000</span></p>\n\n<p><span class="newStyle"\n\nstyle="left: 100px\n\nstyle="top: 222px\n\nstyle="height: 222px\n\nstyle="width: 222px\n\n">001</span></p>\n'
>>> 
于 2012-12-09T16:46:08.350 に答える