简体   繁体   中英

Search a text file for a word then print the next word from text file?

  • The text file lists words in a single column
  • Open this file
  • search the file for 'word'
  • print the the next word from the file after finding 'word'

I've been looking for hours for this syntax, but it must be so simple nobody feels the need to have it written anywhere. Please help

Basic file read:

ifs = open('myfile', 'r')
for line in ifs:
    # do your stuff

Of course, you'll have to deal with special cases of 'word' isn't in the file or it's on the last line in the file.

If the text file is small, you can simply do:

with open('myfile', 'r') as f:
    f = f.read().splitlines() # no trailing '\n' character as opposed to readlines

ind = f.index('word')
if ind < len(f) - 1:
    print(f[ind+1])

If the text file is large, you can read it line by line like this:

with open('myfile', 'r') as f:
    for line in f:
        if line.strip() == 'word':                
            try:
                print(next(f))
            except StopIteration:
                pass
            break

Here is one way to do it:

with open('input') as in_file:
    for line in in_file:
        if line.strip().lower() == 'word':
            line = next(in_file)
            print line.strip()

The above code on an input file as:

word
hello
how
are
you 
word
nadal

prints:

hello
nadal

Hope it helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM