用Python在大文件中查找单词的最后出现位置
我有一个非常大的文本文件。我想找到某个特定单词最后出现的位置,然后对它后面的几行进行一些操作。
我可以这样做:
if "word" in line.split():
do something
不过,我只对这个单词最后出现的地方感兴趣。
5 个回答
0
如果你的文件太大,无法一次性全部加载到内存中,而且你要找的单词更可能出现在文件的后半部分,那么你可以使用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
就是你要寻找的那个字符串。
2
你可以打开你的文件,把它变成一个列表,然后把列表的顺序反转,再一个一个查找你想要的词。
with 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_:
4
可以这样试试:
f = open('file.txt', 'r')
lines = f.read()
answer = lines.find('word')
然后你可以从中选出最后一个单词
你也可以使用 str.rfind
str.rfind(sub[, start[, end]])
这个方法会返回在字符串中找到的子字符串 sub 的最高索引,也就是说 sub 在 s[start:end] 这个范围内的位置。可选的参数 start 和 end 就像切片那样使用。如果找不到,返回 -1。
5
如果文件的大小有几百兆甚至几个吉字节,那你可能想用 mmap,这样就不需要把整个文件都读到内存里。rfind 方法可以找到文件中某个字符串最后出现的位置。
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()
来读取后面的行。
如果文件特别大(比如有十几个吉字节),你可以用 mmap()
的 length 和 offset 参数来分块映射文件。
8
其实,有一个更简单、更快的方法,就是反着打开文件,然后找到你想要的第一个单词的位置。
在Python 2.6中,你可以这样做(其中word是你要查找的字符串)
for line in reversed(open("filename").readlines()):
if word in line:
# Do the operations here when you find the line