使用python查找大文件中最后一次出现的单词 [英] Find the last occurrence of a word in a large file with python

查看:33
本文介绍了使用python查找大文件中最后一次出现的单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常大的文本文件.我想搜索特定单词的最后一次出现,然后对它后面的行执行某些操作.

I have a very large text file. I want to search for the last occurrence of a specific word and then perform certain operations on the lines that follows it.

我可以这样做:

if "word" in line.split():
    do something

不过,我只对 "word" 最后一次出现感兴趣.

I am only interested in the last occurrence of "word" however.

推荐答案

一个更简单快捷的解决方案是以相反的顺序打开文件,然后搜索第一个单词的位置.

Well an easier and quicker solution would be to open the file in reversed order and then searching the first word location.

在 python 2.6 中,您可以执行类似操作(其中 word 是您要查找的字符串)

In python 2.6 you can do something like (where word is string you are looking for)

for line in reversed(open("filename").readlines()):
    if word in line:
    # Do the operations here when you find the line

这篇关于使用python查找大文件中最后一次出现的单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆