0

我正在用 Python 创建一个词云程序,但我被困在一个词替换功能上。我正在尝试用有序列表中的单词替换 html 文件中的一组数字(所以我正在使用字符串)。因此 000 将替换为列表中的第一个单词,001 将替换为第二个单词,依此类推。

下面的方法在通过相对简单的字符串时有效:

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

不幸的是,对于这类问题,您的方法是完全错误的,因为它们是模板引擎的良好候选者。

您可以尝试使用可用模板引擎的数量,或者我可以建议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 回答