python中的拆分标记

2024-09-30 16:32:14 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

提取{{today}}{{runner_up}}等的最佳或最具Python式的方法是什么。?在

我知道可以用split/regular表达式来完成,但我想知道是否还有其他方法。在

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

编辑:我认为这个HTML示例很糟糕,因为它指导了一些注释者美化组。因此,这里有一个新的输入数据:

^{pr2}$

输出:

spelling
mistakes
author

Tags: 文件数据方法hellotodaytitlehtmlbody
3条回答

我不知道,但我不能帮你

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

编辑:JFS

比较:

^{pr2}$

嗯,这里有一个发电机解决方案,似乎对我很有效。如果您愿意,还可以提供不同的打开和关闭标记。在

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

针对目标输入运行,如下所示:

^{pr2}$

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

试试templatemaker,一个反向模板生成器。它实际上可以自动从例子中学习它们!在

相关问题 更多 >