亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在字典中的不同行上組織相等的正則表達式匹配

在字典中的不同行上組織相等的正則表達式匹配

陪伴而非守候 2021-10-10 14:38:40
我正在嘗試提取正則表達式出現的元數據。特別是我堅持如何(最好)提取發生匹配的文本行。當有多個相等的匹配時,問題就出現了。因此,我編寫了一個小腳本來提取所需的模式并使用 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})


查看完整回答
反對 回復 2021-10-10
?
守候你守候我

TA貢獻1802條經驗 獲得超10個贊

只需遍歷行,每當您找到匹配項時,就會增加一個計數器變量。


查看完整回答
反對 回復 2021-10-10
  • 2 回答
  • 0 關注
  • 178 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號