使用下面的python我试图找到带有markdown文件的特定标题
import re
source_file = open('readme.md')
#Defines variables containing the headings as Regex searches
product_name = re.compile('(?mi)^#+[^\S\n]product.*name')
product_version = re.compile('(?mi)^#+[^\S\n]product.*version')
product_description = re.compile('(?mi)^#+[^\S\n]product.*description')
#Adds the required headings to a list
headings = [product_name, product_version, product_description]
#Opens the readme, searches for the specified headings, then uses print_section to print the content under the headings
with open('readme.md') as file:
for x in headings:
content = x.search(file.read()).group(0)
print(content)
readme.md文件包含以下占位符文本
# Product Name
Test Product
## Product Version
0.01
## Product Description
A short overview of what this product is; what it does; and what its intended use case is
# Specifications
## Networking
the quick brown fox jumped over the lazy dog
## Data Usage
This is line one of the sample
This is line two of the sample
我从运行此文件得到的响应是:
# Product Name
Traceback (most recent call last):
File "sample.py", line 16, in <module>
content = x.search(file.read()).group(0)
AttributeError: 'NoneType' object has no attribute 'group'
所以我认为第二个和第三个Regex模式存在问题。但是在正则表达式测试器中,它们似乎可以正确匹配。我无法真正发现这些模式与第一个成功的模式之间的任何区别,甚至尝试交换markdown文件中内容的顺序,但仍然只有product_name匹配。
仅读取一次文件,然后搜索:
with open('readme.md') as file:
f = file.read()
for x in headings:
content = x.search(f).group(0)
print(content)
Python一旦read()
到达文件末尾(基本上是在第一次迭代后),它将继续返回空字符串。而且,由于搜索空字符串,您会不断收到NoneType错误。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句