文件格式如下:
Component_name - version - author@email.com - multi-line comment with new lines and other white space characters
\t ...continue multi-line comment
Component_name2 - version - author2@email.com - possibly multi-line comment with new lines and other white space characters
Component_name - version - author@email.com - possibly multi-line comment with new lines and other white space characters 2
Component_name - version - author2@email.com - possibly multi-line comment with new lines and other white space characters 2
and so on...
解析后的输出格式应按 component_name 分组:
output = [
"component_name" -> ["version - author@email.com - comment 1", "version - author@email.com - comment 2", ...],
"component_name2" -> [...],
...
]
目前,这是我目前要解析的内容:
reTemp = r"[\w\_\-]*( \- )(\d*\.?){3}( \- )[\w\d\_\-\.\@]*( \- )[\S ]*"
numData = 4
reFormat = re.compile(reTemp)
textFileLines = textFile.split("\n")
temp = [x.split(" - ", numData - 1) for x in textFileLines if re.search(reFormat, x)]
m = filter(None, temp) # remove all empty lists
group = groupby(m, lambda y: y[0].strip())
这对单行注释很有效,但对多行注释无效。另外,我不确定 Regex 是否是适合此目的的工具。有没有更好的/pythonic 方法来做到这一点?
编辑:
- 多行注释以制表符分隔
\t另起一行(例如,查看上面的第一个条目) - 评论是 GIT 提交消息,可以包含 JSON 或代码
- 条目由换行符分隔
请您参考如下方法:
我不得不处理这样的结构化数据文件,最后编写了一个状态机来解析文件。像这样的东西(粗略的伪代码):
for line in file:
if line matches new_record_regex:
records.append(record)
record = {"version": field1, "author": field2, "comment": field3}
else:
record["comment"] += line
