我想搜索像frame1()、frame2()、frame3()这样的模式“frame(一些变量数)”的最后出现.(它不完全是字符串)。我有兴趣得到变量数,它将随着每一次的发生而不断增加。
我通过使用这段代码和获得正确的答案()来做到这一点,但是我想要更有效的解决方案。
regex = re.compile('frame*[0-9]*\(\)') NoOfFrames = len(regex.findall(textfile))
但我认为可能有更有效的方法来找到它,而不是列出所有的事件,然后计算它。就像我们可以从文本文件的最后一行开始,那么第一个出现的就是答案。我也试过用这个
m = mmap.mmap(file.fileno(), 0, access=mmap.ACCESS_READ) i = m.rfind(regex) # search for last occurrence of 'word' print(i) m.seek(i) # seek to the location line = m.readline() # read to the end of the line print(line)
但这是行不通的,因为我正在搜索的并不完全是一个字符串。我的文本文件非常大,类似于千兆字节,更有效的解决方案将受到赞赏。
谢谢!
发布于 2019-07-08 07:40:17
我得到了答案。我们可以使用正则表达式模块,该模块具有向后搜索模式的方法。
with open('a.txt', 'r') as file: textfile = file.read() output = regex.search(r"(?r)frame*[0-9]*\(\)", textfile) print(output.group(0))
这将发现帧*0-9*()从后向第一次出现,并且输出将采用_regex.Match格式。要将其转换为字符串,我们可以使用output.group(0)。
谢谢!
发布于 2019-07-02 09:18:48
您可以使用$符号来匹配字符串的末尾(regex101):
data = '''frame1() text
frame2() text text
text frame3()
another text'''
import re
print(re.findall(r'.*frame([0-9]+)\(\).*?$', data, flags=re.DOTALL))指纹:
['3']https://stackoverflow.com/questions/56849016
复制相似问题