[英]How to read HTML file only within a certain block in python?
我正在尝试仅在 python 的特定块(神社模板)内读取 HTML 文件。 我想在 {% block content %} 和它对应的 {% endblock %} 之间阅读。
我正在块之间搜索 {{ 和 {% ,我想打印行号和找到搜索模式的行的内容。
我将文件路径保存在一个变量中,并在需要时使用它来打开文件。 我使用枚举 function 来跟踪行号。
fp = r"<path_to_HTML_file>"
def scan(line_number, line, flag):
with open(fp, 'r', encoding='utf-8') as f:
for check_line_number, check_line in enumerate(f, 1):
if check_line_number >= line_number:
if '{%' in check_line:
print("Line Number: {}\nContent: {}".format(check_line_number, check_line))
with open(fp, 'r', encoding='utf-8') as f:
for line_number, line in enumerate(f, 1):
if '{% block content %}' in line:
flag = 1
scan(line_number, line, flag)
我面临的问题是我的代码打印出所有出现在 {% block content %} 之后的 {%,但我想读到相应的 {% endblock %}。
另外,我不确定在哪里关闭文件。
使用正则表达式可以很容易地解决这个问题。
import re
# blocks will be a list of the contents of the blocks in the string FILE_CONTENTS
blocks = re.findall(r'{% block \w+? %}(.*?){% endblock %}', FILE_CONTENTS, re.S)
我强烈建议您通读正则表达式模式。 它们非常方便。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.