Wir*_*ess 5 python regex iterable dictionary-comprehension
我是Python的新手,我正在尝试解析一个文件.只有文件中的某些行包含感兴趣的数据,我想最终得到从文件中的有效匹配行解析的内容的字典.
下面的代码有效,但它有点难看,我正在尝试学习它应该如何完成,也许是理解,或者使用多行正则表达式.我正在使用Python 3.2.
file_data = open('x:\\path\\to\\file','r').readlines()
my_list = []
for line in file_data:
# discard lines which don't match at all
if re.search(pattern, line):
# icky, repeating search!!
one_tuple = re.search(pattern, line).group(3,2)
my_list.append(one_tuple)
my_dict = dict(my_list)
Run Code Online (Sandbox Code Playgroud)
你能建议更好的实施吗?
感谢您的回复。把它们放在一起后我得到了
file_data = open('x:\\path\\to\\file','r').read()
my_list = re.findall(pattern, file_data, re.MULTILINE)
my_dict = {c:b for a,b,c in my_list}
Run Code Online (Sandbox Code Playgroud)
但我认为如果没有帮助,我今天无法到达那里。
这是对代码的一些快速的“肮脏”优化:
my_dict = dict()
with open(r'x:\path\to\file', 'r') as data:
for line in data:
match = re.search(pattern, line)
if match:
one_tuple = match.group(3, 2)
my_dict[one_tuple[0]] = one_tuple[1]
Run Code Online (Sandbox Code Playgroud)