[英]Split the string in a list and match the last splitted string in python
我有一長串這個
| 0x60000000 | _loc_NO_BOOL_CONST_GROUP
| 0x60000020 | _loc_NO_BOOL_GROUP
| 0x60000020 | _loc_NO_BOOL_TEXT_GROUP
| 0x6000ffe0 | _loc_NE_BOOL_GROUP
| 0x6000ffe0 | _loc_NE_BOOL_TEXT_GROUP
| 0x60010000 | _loc_NO_FIXED_DATA_GROUP
| 0x60013dc0 | _loc_NE_BOOL_CONST_GROUP
| 0x60013dc0 | _loc_NE_FIXED_DATA_GROUP
我需要拆分_loc_NO_
和_loc_NE_
並且必須匹配拆分后的 LAST STRING,如果找到匹配項,則返回相應的值。
假設在_loc_NO_BOOL_CONST_GROUP
中我們拆分_loc_NO_
最后一個字符串是BOOL_CONST_GROUP
在_loc_NE_BOOL_CONST_GROUP
中我們拆分_loc_NE_
最后一個字符串是BOOL_CONST_GROUP
兩個字符串都匹配,所以現在,我必須返回相應的值,即“0x60000000”和“0x60013dc0”
所以 output 應該是這樣的:
BOOL_CONST_GROUP = 第一個地址值(即 0x60000000),第二個地址值(即 0x60013dc0)。
同樣 BOOL_TEXT_GROUP = 第一個地址值,第二個地址值
在我看來,這是使用正則表達式的好地方。 這是一個完整的工作解決方案,其中包含從您的示例中推斷出的一些額外限制。
推斷規則:
import re
from collections import defaultdict
strings_to_find = ['_loc_NO_', '_loc_NE_']
pat = re.compile(
r'\| (?P<location>0x[0-9a-f]{8}) ' +
r'\| (?P<instruction>%s)' % '|'.join(strings_to_find) +
r'(?P<instruction_detail>.*?)$',
re.MULTILINE | re.DOTALL)
with open('datafile.txt', 'r', encoding='utf-8') as infile:
data = infile.read()
results = defaultdict(list)
matches = pat.finditer(data)
for m in matches:
results[m.group('instruction_detail')].append(m.group('location'))
for k, v in results.items():
print(k, v)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.