【问题标题】:Fix broken html element in list修复列表中损坏的 html 元素
【发布时间】:2013-09-10 17:16:11
【问题描述】:

这个列表看起来像这样

words = ['how', 'much', 'is</b>', 'the', 'fish</b>', 'no', 'really']

我想在每个以&lt;/b&gt; 结尾的字符串的开头添加&lt;b&gt;,而不会丢失单词序列。

words = ['how', 'much', '<b>is</b>', 'the', '<b>fish</b>', 'no', 'really']

到目前为止,我已经详细说明了很多,因此不胜感激!

谢谢!

【问题讨论】:

    标签: python string list replace find


    【解决方案1】:
    >>> words = ['how', 'much', 'is</b>', 'the', 'fish</b>', 'no', 'really']
    >>> words = ['<b>'+i if i.endswith('</b>') else i for i in words]
    >>> words
    ['how', 'much', '<b>is</b>', 'the', '<b>fish</b>', 'no', 'really']
    

    【讨论】:

      【解决方案2】:

      如果您希望它更通用并适用于所有标签,您可以执行以下操作:

      import re
      
      def change_word(word):
          m = re.search(r'^.*</(.*)>$', word)
          return "<{0}>{1}".format(m.group(1),word)
      
      words = ['how', 'much', 'is</b>', 'the', 'fish</b>', 'no', 'really</div>']      
      words = [change_word(i) if re.match(r'^.*</(.*)>$', i) else i for i in words]
      print words
      

      结果:

       ['how', 'much', '<b>is</b>', 'the', '<b>fish</b>', 'no', '<div>really</div>']
      

      【讨论】:

        猜你喜欢
        • 2011-06-08
        • 2011-09-04
        • 2021-10-26
        • 2010-09-25
        • 1970-01-01
        • 1970-01-01
        • 2019-11-29
        • 2010-11-23
        相关资源
        最近更新 更多