gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 03:26:19 25 4
gpt4 key购买 nike

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

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

最佳答案

您可以使用字典来保存您的正则表达式并通过简单的索引访问它们,可以将相对行数作为键并使用 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)

关于python - 如何为文件中的每一行使用不同形式的正则表达式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32848053/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com