Python解析器脚本布局
我正在写一个简单的Python解析器,主要是逐行读取一个文件,如果满足特定条件,就进一步处理这些行。以下是我开始的代码:
def identify(hh_line):
if(re.match(regex.new_round, hh_line)):
m = re.match(regex.new_round, hh_line)
# insert into psql
...
if(re.match...
我在想,做这个任务的最佳方法是什么,因为这是我第一次写Python。
谢谢!=)
1 个回答
3
首先,重复运行匹配操作是多余的——你可以只运行一次,然后把结果存起来,接着根据这个结果进行后续操作:
m = re.match(regex.new_round, hh_line)
if m:
# ...
接下来,如果你有很多正则表达式和处理的组合,倒不如把正则表达式和对应的函数放在一个字典里,然后直接遍历这个字典:
def process_a(data):
# ...
def process_b(data):
# ...
regex_to_process = {
'regex_a': process_a,
'regex_b': process_b,
}
for hh_line in <file object>:
for regex,process in regex_to_process.iteritems():
m = re.match(regex, hh_line)
if m:
process(hh_line)