如何为文件中的每一行使用不同形式的正则表达式?

时间:2015-09-29 15:30:55

标签: python regex line

with open('ch4_int_coord.txt') as f:
    for line in f:
        line1 = re.search(r'\w{1,2}', f)
        line2 = re.search(r'\w{1,2}\s+(\d+)\s+\d+\.+\d+', int_coord)
        print line1

这是我到目前为止所拥有的。我正在尝试为文件中的每一行使用一个新的正则表达式模式(因为每个行都有不同的数据量),但我不知道如何指定它。

1 个答案:

答案 0 :(得分:2)

您可以使用字典保留正则表达式并使用简单的索引访问它们,可以将相对行数作为键并使用enumerate函数迭代文件对象以访问该行索引。

regex_dict={1:r'\w{1,2}',2:r'\w{1,2}\s+(\d+)\s+\d+\.+\d+'}
with open('ch4_int_coord.txt') as f:
    for index,line in enumerate(f,1):
        print re.search(regex_dict[index],line)