元素不在Python 3的列表中
我使用的是Python3,我想识别一个单词是否在文本文件中 文本文件的内容:元素不在Python 3的列表中,python,Python,我使用的是Python3,我想识别一个单词是否在文本文件中 文本文件的内容: test test test 我的代码: wordsUsedFilename = "usedwords.txt" f = open(wordsUsedFilename, 'r') usedWords = [line.strip() for line in f] words = [] words.append("test") check = True while check: for word in w
test
test
test
我的代码:
wordsUsedFilename = "usedwords.txt"
f = open(wordsUsedFilename, 'r')
usedWords = [line.strip() for line in f]
words = []
words.append("test")
check = True
while check:
for word in words:
if word not in usedWords:
print("Not in the list")
else:
print("In the list")
check = False
问题是程序应该停止,但考虑到单词不在列表中,它会继续运行,我做错了什么 您的问题在于:
f = open(wordsUsedFilename, 'a+')
'a+'
模式附加到文件末尾。。。这也是它开始读取文件的地方。将其更改为'r'
,您将获得金牌
另外,您最好使用set
存储单词列表:
usedWords = set()
with open(wordsUsedFilename, 'r') as f:
for line in f:
usedWords.add(line.strip())
事情是这样的:
wordsUsedFilename = "usedwords.txt"
usedWords = set()
with open(wordsUsedFilename, 'r') as f:
for line in f:
usedWords.add(line.strip())
words = []
words.append("test")
for word in words:
if word not in usedWords:
print("Not in the list")
else:
print("In the list")
这对我很有用:
$ more usedwords.txt
test
test
test
$ python practice.py
In the list
对于您似乎正在做的事情,您可以对照整个数据块进行检查
wordsUsedFilename = "usedwords.txt"
words = ["test"]
f = open(wordsUsedFilename, 'r')
text= f.read()
for word in words:
if word in text:
print("{} in {}".format(word, wordsUsedFilename))
我看到一个无限循环,但如果单词不在单词中,代码中没有
中断,
将永远不会是真的,因为单词刚从单词中出来,经过四次更正,但仍然不起“中断”作用?我真的应该休息一下吗?如果为false,它将停止运行,不是吗?第一次迭代,假设它为
循环耗尽,当
的条件为false时,它将检查。这永远不会是真的。因此,while
循环将被无限次执行。@thefourtheye谢谢我清理了代码,但仍然得到了相同的错误,正如您所看到的,它现在更明确了,它将继续写“不在列表中”,我确信测试词在我的列表中。非常感谢MikeThanks的选择