【问题标题】:Replacing words in string with items in a list用列表中的项目替换字符串中的单词
【发布时间】:2012-12-09 14:48:42
【问题描述】:

我正在用 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            

【问题讨论】:

  • 使用标准的Python字符串格式化功能不是更好吗? '{0}, {1}, {2}, {3}'.format(*word) 将获得相同的结果。
  • 这样你会把1000变成1foo。
  • 你为什么接受my answeryour last question,然后继续使用一个坏掉的版本?此外,您可以通过使用String Formatting syntax 和仅使用str.format() 来让自己更轻松。
  • @Lattyware 我有点新手,很抱歉有任何困惑。据我了解,我确实使用您的答案来解决这个问题。它适用于更简单的字符串,但不适用于“html 字符串”。所以当我在我的 HTML 文件上应用上述方法时,它并没有像我预期的那样工作。

标签: python string list enumerate


【解决方案1】:

类似的东西最好写成(对于你的非 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'

【讨论】:

  • 文中还有291px之类的东西,这样就不行了。
  • @BrtH 非常好 - 指的是原始的非 HTML 文本内容
  • 确实如此。顺便说一句,对于非 html 文本,re.sub(r'\d+', lambda m:word[int(m.group(0))], text) 会更简单。
  • 是否可以使用正则表达式对 HTML 文本字符串进行列表替换?
  • @NightMarcher 您必须使用 lxml.htmlBeautifulSoup 之类的东西来获取您的文本内容,然后修改...
【解决方案2】:

不幸的是,对于这类问题,您的方法是完全错误的,因为它们是 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'
>>> 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-12-03
    • 1970-01-01
    • 2012-11-26
    • 2015-07-03
    • 2019-08-04
    相关资源
    最近更新 更多