python - 在 python 中拆分标签

标签 python split template-engine

我有一个包含这个的文件:

<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

最佳答案

嗯,好吧,这是一个似乎对我来说效果很好的生成器解决方案。如果愿意,您还可以提供不同的开始和结束标签。

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

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

关于python - 在 python 中拆分标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/571186/

相关文章:

python - 在 python 中用子列表拆分字符串

javascript - JQuery 函数访问

R 将语料库分解为句子

C#模板引擎

java - 如何用java生成脚本代码?

c++ - 从 C++ 调用 Python 函数

python - 无法使用 Asyncore Python 接收数据

php - 使用 Dwoo 在 Codeigniter 模板中的 View 中包含 View 的最佳方法?

python - Twython - 如何将多个 Twitter 帐户与一个用户关联

python slice() 函数 vs slice notation - 如何处理 slice() 中的空值?