简体   繁体   English

为什么我的 for 循环无限期地运行并且在满足 if 条件时不会停止?

[英]Why does my for loop run indefinitely and doesn't stop when the if condition is met?

I'm trying to read text from a file and using a loop to find a specific text from the file.我正在尝试从文件中读取文本并使用循环从文件中查找特定文本。 The data in the file is listed vertically word by word.文件中的数据逐字垂直列出。 When I run the script, after it prints the last word in the file it repeats itself from the beginning indefinitely.当我运行脚本时,在它打印文件中的最后一个单词后,它会从头开始无限重复。

with open('dictionary.txt','r') as file:
    dictionary = file.read().strip()
for i in dictionary:
 print (dictionary)
 if( i == "ffff" ):
    break

first split the lines by "\n" then print(i) not print(dictionary) :首先将行拆分为"\n"然后print(i)不是print(dictionary)

with open('dictionary.txt', 'r') as file:
    dictionary = file.read().strip().split("\n")
for i in dictionary:
    print(i)
    if i == "ffff":
        break

before, you should split the lines b/c it will loop into the string and check if the characters are ffff , and it won't be True之前,您应该split行 b/c 它将循环到字符串中并检查字符是否为ffff ,它不会是True

i will be a single character, so you should do first我将是一个单一的角色,所以你应该先做

dictionary = dictionary.split("\n")

BUT if your ffff is a line, if is a word separated with spaces you can do:但是如果你的ffff是一行,如果是一个用空格分隔的单词,你可以这样做:

dictionary = dictionary.split(" ")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 满足条件时while循环不会停止 - While loop does not stop when the condition is met 为什么当条件变为 False 时 while 循环不停止? - Why doesn't the while loop stop when the condition becomes False? 即使条件不满足,Python while 循环也不会停止 - Python while loop won't stop even when condition not met ATBSWP,第3章,Collat​​z序列。 为什么在条件已满足的情况下运行while循环? - ATBSWP, Chapter 3, Collatz Sequence. Why does the while loop run when condition is already met? 条件满足时停止 for 循环或 while 循环 - Stop for loop or while loop when condition met 不知道为什么在满足条件时插入元素不起作用 - not sure why inserting element doesn't work when condition is met 为什么我的函数在满足条件时不执行? - Why does my function not execute when the condition is met? while 循环没有结束但条件满足 - The while loop doesn't end but the condition is met 为什么我的while循环停止了? - Why doesn't my while loop stop? 为什么'无法读取缓存在:.cache-<my username> ' 在 Spotipy 中进行身份验证时出现警告并且代码无限期运行?</my> - Why does the 'couldn't read cache at: .cache-<My Username> ' warning appear and the code run indefinitely when authenticating in Spotipy?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM