【问题标题】:How to iterate through a file once a word is found找到单词后如何遍历文件
【发布时间】:2017-06-15 13:10:26
【问题描述】:

我正在文本文件中搜索输入词。但是,我只打算在“START”一词之后搜索文件中的文本。 “START”之前的前二十位应该被忽略。我知道如何找到“START”,但不知道如何在遇到“START”后搜索文件的其余部分。我会很感激任何指导!

这是我目前所拥有的:

file = open("EnglishWords.txt", "r")

print("***** Anagram Finder *****")
word = input("Enter a word: ")


for line in file:
    if "START" in line:
        if word in line:
            print("Yes, ", word, " is in the file.", sep="")
        else:
            print("Sorry, ", word, " is not in the file.", sep="")


file.close()

这是文本文件的示例:

    The name of Princeton University or Princeton may not be
     used in advertising or publicity pertaining to
     distribution of the software and/or database.  Title to
     copyright in this software, database and any associated
     documentation shall at all times remain with Princeton
     University and LICENSEE agrees to preserve same.
START
clobber
transversalis
squinter
cunner
damson
extrovertive
absorptive

【问题讨论】:

  • 如何迭代?逐词地?逐行?基本上你阅读直到你找到开始,然后继续阅读。你如何继续取决于你如何开始。即......到目前为止你有什么?
  • 您能否edit your question 提供您的文本文件示例以及您想要在其中找到的内容。
  • 同意@MartinEvans。文件格式/样式是什么?是一行一行的吗?还是段落样式?这将改变扫描方法。
  • 我已经编辑包括我迄今为止的尝试...
  • this 可能重复?

标签: python python-3.x file


【解决方案1】:

修改您的代码,我们有

file = open("EnglishWords.txt", "r")

print("***** Anagram Finder *****")
word = input("Enter a word: ")


start_looking = False
word_found = False

for line in file:
    if not start_looking:
        if "START" in line:
            start_looking = True
        else:
            continue

    if word in line:
        print("Yes, ", word, " is in the file.", sep="")
        word_found = True
       break

if not word_found:
    print("Sorry, ", word, " is not in the file.", sep="")

file.close()

只要没有找到START,就一直跳过文件的行。但是,如果您遇到START,请重置您的标志并开始查找。

【讨论】:

  • 这将为'Start' 之后的每一行打印"Sorry...",直到找到单词。
  • @ason​​gtoruin 啊,感谢您指出这一点。专注于另一个错误,没有看到这个。
  • 不用担心 - 我在你之后几秒钟发布了一个几乎相同的答案,但由于你对 continue 的使用比我使用的第二个 if 更简洁一些,所以我将其删除。
  • 谢谢! (我的级别太低,无法 +1)。
  • @Coldspeed 对不起,其他的有点整洁! ;)
【解决方案2】:

找到您的单词后发送for

with open(myfile, 'r') as f:
    for line in f:
        if 'START' in line:
            # do stuff to lines below 'START'
            # you could do another for loop here to iterate
            for line in f:
                print (line) # just an example

this 其他 SO 帖子非常相似。我的答案语法的功劳来自它的答案。

【讨论】:

  • 谢谢,这是最巧妙的解决方案!
【解决方案3】:

正则表达式模块怎么样?

re.findall(r"START.*(word_to_search).*", entire_text)

只有在要搜索的单词之前有一个 START 时,它才会返回结果。我希望这就是你要找的。​​p>

编辑: 对于逐行的解决方案,我会使用类似的东西:

start_search = 0
    with open(bigfile, "r") as f:
        for line in f:
            if "START" IN line:
                start_search = 1
            if start_search and word_to_search in line:
                print("result foun")
                return (word_to_search)

这个呢?

【讨论】:

  • 这是一个优雅的解决方案,但是如果文件很大并且应该逐行读取怎么办?
  • 文件不是很大,但我需要逐行阅读以完成作业...
  • 谢谢! (我的级别太低,无法 +1)。
【解决方案4】:

保持简短、简单和明确:

with open("EnglishWords.txt", 'r') as fin:
    output = fin.readlines()
    # Find the line that contains START
    index = output.index("START")
    # Search all the lines after that
    for line in output[index+1:]:
        if word in line:
            print("Yes, ", word, " is in the file.", sep="")
        else:
            print("Sorry, ", word, " is not in the file.", sep="")

【讨论】:

  • 谢谢! (我的级别太低,无法 +1)。
【解决方案5】:

您可以使用 Python 的 dropwhile() 来定位单词的开头并从那里迭代:

from itertools import dropwhile

print("***** Anagram Finder *****")
word = input("Enter a word: ").lower() + '\n'

with open("EnglishWords.txt") as f_words:
    if word in dropwhile(lambda r: not r.startswith("START"), f_words):
        print("Yes, {} is in the file".format(word.strip()))
    else:
        print("Sorry, {} is not in the file.".format(word.strip()))

【讨论】:

    【解决方案6】:

    您可以使用布尔值:

    file = open(“testfile.txt”, “r”) 
    foundStart = False
    for line in file: 
        if foundStart:
             # do something...
        elif line == "START":
           foundStart = True
    

    【讨论】:

    • 好吧,他没有分享他的代码,所以我提供了另一种方法来找到它;)
    • @Xatyrian 我不认为提供另一种方法来做他已经知道的事情可以作为他问题的答案。 :)
    猜你喜欢
    • 2023-03-17
    • 1970-01-01
    • 2021-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-21
    • 2014-08-26
    • 1970-01-01
    相关资源
    最近更新 更多