簡體   English   中英

在文本文件中搜索單詞,然后從文本文件中打印下一個單詞?

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

  • 文本文件在單列中列出單詞
  • 打開這個文件
  • 在文件中搜索“ word”
  • 找到“單詞”后,從文件中打印下一個單詞

我一直在尋找這種語法的時間,但是它必須如此簡單,沒人會覺得需要在任何地方編寫它。 請幫忙

基本文件讀取:

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

當然,您必須處理'word'不在文件中或在文件的最后一行的特殊情況。

如果文本文件很小,則可以執行以下操作:

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])

如果文本文件很大,您可以這樣逐行閱讀:

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

這是一種實現方法:

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

上面的代碼在一個輸入文件上為:

word
hello
how
are
you 
word
nadal

印刷品:

hello
nadal

希望能幫助到你

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM