[英]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.