我的问题如下:
def searchWordlist():
path = str(raw_input(PATH))
word = str(raw_input(WORD))
with open(path) as f:
for line in f:
if word in line:
print "Word found"
比我添加以下代码:
else:
print "Word not found"
但这显然无法奏效,因为它会打印出#34; Word not found"直到找到这个词。嗯..但是如何打印出找不到的单词?!我不知道。
提前谢谢!
答案 0 :(得分:4)
Python有一个特殊的技巧:
else
此处for
与break
一致,如果循环正常完成而没有点击{{1}},则专门执行。
答案 1 :(得分:3)
如果您只想打印是否在任何一行中找到word
:
def searchWordlist():
path = str(raw_input(PATH))
word = str(raw_input(WORD))
with open(path) as f:
if any(word in line for line in f):
print('Word found')
else:
print('Word not found')
答案 2 :(得分:1)
def searchWordlist():
path = str(raw_input(PATH))
word = str(raw_input(WORD))
loc = -1
with open(path) as f:
for i, line in enumerate(f):
if word in line:
loc = i
break
if loc >= 0:
print ("Word found at line {}".format(loc))
else:
print ("Word not found")
作为奖励,这会记录文件中首次出现的字词,如果有的话。
答案 3 :(得分:1)
如果您只需找到第一个匹配项,则可以在找到单词后立即返回函数。如果不需要
,这还有额外的好处,就是不必遍历整个文件def searchWordlist():
path = str(raw_input(PATH))
word = str(raw_input(WORD))
with open(path) as f:
for line in f:
if word in line:
print "Word found"
return 1
print "Word not found"
return 0
答案 4 :(得分:0)
def searchWordlist():
found_word = False
path = str(raw_input(PATH))
word = str(raw_input(WORD))
with open(path) as f:
for line in f:
if word in line:
print "Word found"
found_word = True
if not found_word:
print "Word not found!"
这段代码的作用是它正常执行你的代码,除非它找到单词,它将布尔值设置为true,表示它已经找到了这个单词。然后,在完全解析文件之后,查看是否找到了该单词,如果该变量为真。如果找不到该单词,则会打印出未找到该单词的单词。如果您希望代码在首次找到该字词后停止,则break
之后found_word = True
会停止。