我是一位有用的助手,可以为您提供翻译。以下是需要翻译的内容:
我有一个非常大的文本文件。我想要搜索特定单词的最后一个出现位置,然后对其后面的行执行某些操作。
我可以这样做:
if "word" in line.split():
do something
但是,我只对最后一次出现的"word"
感兴趣。
我有一个非常大的文本文件。我想要搜索特定单词的最后一个出现位置,然后对其后面的行执行某些操作。
我可以这样做:
if "word" in line.split():
do something
但是,我只对最后一次出现的"word"
感兴趣。
一个更简单且更快的解决方案是以相反顺序打开文件,然后搜索第一个单词的位置。
在Python 2.6中,您可以执行以下操作(其中word是要查找的字符串)
for line in reversed(open("filename").readlines()):
if word in line:
# Do the operations here when you find the line
import mmap
with open('large_file.txt', 'r') as f:
# memory-map the file, size 0 means whole file
m = mmap.mmap(f.fileno(), 0, prot=mmap.PROT_READ)
# prot argument is *nix only
i = m.rfind('word') # search for last occurrence of 'word'
m.seek(i) # seek to the location
line = m.readline() # read to the end of the line
print line
nextline = m.readline()
只需不断调用readline()
来读取后续行。
如果文件非常大(例如数十GB),则可以使用mmap()
的length和offset参数将其分块映射。
f = open('file.txt', 'r')
lines = f.read()
answer = lines.find('word')
然后你可以从中选择最后一个单词
您还可以使用str.rfind方法。
str.rfind(sub[, start[, end]])
"name" in "protect your enamel".split()
与 "protect your enamel".rfind("name")
进行比较。 - DSMwith open('file.txt','r') as file_:
line_list = list(file_)
line_list.reverse()
for line in line_list:
if line.find('word') != -1:
# do something
print line
可选地,您可以通过将缓冲区大小(以字节为单位)作为 open
的第三个参数来指定文件缓冲区的大小。例如:with open('file.txt','r', 1024) as file_:
file_read_backwards
库来反向读取文件。from file_read_backwards import FileReadBackwards
with FileReadBackwards(filename, encoding="utf-8") as frb:
for line in frb:
if word in line:
# Do something
其中filename
包含文件名,word
是你要查找的字符串。