试图对问题使用不同的标题,但如果您可以改进问题,请这样做。Python - 如何在Python中逐行使用正则表达式
这里是我的正则表达式:f\(\s*([^,]+)\s*,\s*([^,]+)\s*\)
我不得不上的文件,一行一行地应用它。一行行可以,简单地从文件中读取数据,然后循环。但是,如何将正则表达式应用于行?
感谢您的所有帮助,并为noob问题感到抱歉。
试图对问题使用不同的标题,但如果您可以改进问题,请这样做。Python - 如何在Python中逐行使用正则表达式
这里是我的正则表达式:f\(\s*([^,]+)\s*,\s*([^,]+)\s*\)
我不得不上的文件,一行一行地应用它。一行行可以,简单地从文件中读取数据,然后循环。但是,如何将正则表达式应用于行?
感谢您的所有帮助,并为noob问题感到抱歉。
使用import re
,然后re.compile()
与您的模式作为参数,并在每行上使用结果对象的match
属性。这样的事情..
import re
pat = re.compile(r'f\(\s*([^,]+)\s*,\s*([^,]+)\s*\)')
for line in file:
# use pat.match, pat.search .. etc
你可以尝试这样的事情:
import re
regex = re.compile("f\(\s*([^,]+)\s*,\s*([^,]+)\s*\)")
with open("my_file.txt") as f:
for line in f:
result = regex.search(line)
import re
with open('file.txt') as f:
for line in f:
match = re.search('f\(\s*([^,]+)\s*,\s*([^,]+)\s*\)', line)
需要注意的是Python的自动编译和缓存正则表达式,所以一个单独的编译步骤是不是在这种情况下,需要。
以下表达式返回一个列表;该列表中的每个条目都包含相应行中正则表达式的所有匹配项。
>>> import re
>>> [re.findall(r'f\(\s*([^,]+)\s*,\s*([^,]+)\s*\)',line)
for line in open('file.txt')]
我已经使用这个形式给出:
import re
#Define the search term:
pattern = f\(\s*([^,]+)\s*,\s*([^,]+)\s*\)
#Create an empty list:
data = []
#then
for line in open(r'file.txt'):
if line !='': #<-- To make sure the whole file is read
word = re.findall(pattFinder1, line)
data.append(str(word))
另一种方法
import re
[line for line in open('file.txt') if re.match(r'f\(\s*([^,]+)\s*,\s*([^,]+)\s*\)',line)]
for line in file:
line = re
.match("f\(\s*([^,]+)\s*,\s*([^,]+)\s*\)",line)
.group(0)
即使你的答案是非常接近从塞德里克朱利安的人,我已经由于列表的理解和解释而投票支持你 – dlewin 2018-01-30 14:22:25