Jon*_*ero 4 python split template-engine
我有一个文件包含这个:
<html>
<head>
<title> Hello! - {{ today }}</title>
</head>
<body>
{{ runner_up }}
avasd
{{ blabla }}
sdvas
{{ oooo }}
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
什么是提取最好的或最Python的方式{{today}},{{runner_up}}等等?
我知道它可以通过分割/正则表达式完成,但我想知道是否还有其他方法.
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}}.
Run Code Online (Sandbox Code Playgroud)
输出:
spelling
mistakes
author
Run Code Online (Sandbox Code Playgroud)
Mmkay,这里是一个似乎对我有用的发电机解决方案.如果您愿意,还可以提供不同的打开和关闭标签.
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
Run Code Online (Sandbox Code Playgroud)
针对您的目标输入运行,如下所示:
# prints: today, runner_up, blabla, oooo
for tag in get_tags(html):
print tag
Run Code Online (Sandbox Code Playgroud)
编辑:它也适用于你的新例子:).在我明显快速的测试中,它似乎也以合理的方式处理格式错误的标签,尽管我不保证其稳健性!