4

我有一个包含以下内容的文件:

<html>
  <head>
    <title> Hello! - {{ today }}</title>
  </head>
  <body>
    {{ runner_up }} 
         avasd
         {{ blabla }}
        sdvas
        {{ oooo }}
   </body>
</html>

{{today}}提取,{{runner_up}}等的最好或最 Pythonic 的方法是什么?

我知道可以使用拆分/正则表达式来完成,但我想知道是否还有其他方法。

PS:考虑加载在一个名为的变量中的数据thedata

编辑:我认为 HTML 示例很糟糕,因为它将一些评论者引导到 BeautifulSoup。所以,这是一个新的输入数据:

Fix grammatical or {{spelling}} errors.

Clarify meaning without changing it.

Correct minor {{mistakes}}.

Add related resources or links.

Always respect the original {{author}}.

输出:

spelling
mistakes
author
4

5 回答 5

8

嗯,这是一个似乎对我很有效的生成器解决方案。如果您愿意,您还可以提供不同的打开和关闭标签。

def get_tags(s, open_delim  ='{{', 
                close_delim ='}}' ):

   while True:

      # Search for the next two delimiters in the source text
      start = s.find(open_delim)
      end   = s.find(close_delim)

      # We found a non-empty match
      if -1 < start < end:

         # Skip the length of the open delimiter
         start += len(open_delim)

         # Spit out the tag
         yield s[start:end].strip()

         # Truncate string to start from last match
         s = s[end+len(close_delim):]

      else:
         return

像这样针对您的目标输入运行:

# prints: today, runner_up, blabla, oooo
for tag in get_tags(html):
    print tag

编辑:它也适用于您的新示例:)。在我明显的快速测试中,它似乎也以合理的方式处理了格式错误的标签,尽管我不保证它的稳健性!

于 2009-02-20T21:09:48.350 回答
3

试试templatemaker,一个反向模板制造商。它实际上可以从示例中自动学习它们!

于 2009-02-20T21:08:00.507 回答
2

我知道你说没有正则表达式/拆分,但我忍不住尝试了一个单行解决方案:

import re
for s in re.findall("\{\{.*\}\}",thedata):
        print s.replace("{","").replace("}","")

编辑:JFS

比较:

>>> re.findall('\{\{.*\}\}', '{{a}}b{{c}}')
['{{a}}b{{c}}']
>>> re.findall('{{(.+?)}}', '{{a}}b{{c}}')
['a', 'c']
于 2009-02-20T21:14:03.567 回答
1

如果数据这么简单,一个简单的正则表达式就可以解决问题。

于 2009-02-20T21:10:17.367 回答
1

JF Sebastian 在评论中写了这个,但我认为它已经足够好,值得拥有自己的答案:

re.findall(r'{{(.+?)}}', thestring)

我知道 OP 正在寻求一种不涉及拆分或正则表达式的方式 - 所以也许这并不能完全回答所述问题。但是这一行代码绝对是我的投票,因为它是完成任务的最 Pythonic 方式。

于 2009-02-20T21:34:59.680 回答