我正在嘗試提取正則表達式出現的元數據。特別是我堅持如何(最好)提取發生匹配的文本行。當有多個相等的匹配時,問題就出現了。因此,我編寫了一個小腳本來提取所需的模式并使用 re.finditer 對其進行循環。但是,我被困在如何最好地“暫?!蔽业难h以返回正確的 match_index 與該行。我覺得生成器可能值得一看,或者我可能忽略了一種開箱即用的方法。執行以下操作的最“pythonic”(并且實際有效)的方法是什么?import restring = """a zero linewe can write pattern_1 herelet's buffer here, just chilling, everything's okI think it's time for a second pattern_2let's a do another pattern_1ciao"""pattern = re.compile(r"\w{7}_\d")found = re.finditer(pattern, string)matches_list = []for match_index, match in enumerate(list(found)): for index, line in enumerate(string.splitlines()): if match.group() in line: match_meta_dict = { 'match_index': match_index, 'line': index } matches_list.append(match_meta_dict) breakprint(matches_list)我想得到一個字典列表,其中該行對應于相應的模式,如下所示:[{'match_index': 0, 'line': 1}, {'match_index': 1, 'line': 3}, {'match_index': 2, 'line': 4}]相反,我得到(顯然):[{'match_index': 0, 'line': 1}, {'match_index': 1, 'line': 3}, {'match_index': 2, 'line': 1}]
2 回答

慕娘9325324
TA貢獻1783條經驗 獲得超4個贊
您確定字典數組是存儲它的最佳數據結構嗎?我認為一個整數數組就足夠了,因為match_index總是從 0 開始并增加 1,所以你真的只需要存儲行號。該行號的索引是匹配索引。如果您堅持使用字典數組,則可以輕松地將行號數組轉換為該數組。
line_numbers = []
for index, line in enumerate(string.splitlines()):
for match in re.finditer(pattern, line):
line_numbers.append(index)
轉換為字典數組:
matches_list = []
for index, line_number in enumerate(line_numbers):
matches_list.append({"match_index": index, "line": line_number})
添加回答
舉報
0/150
提交
取消