林的Python检查表行

2024-10-01 07:48:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我的问题是:

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"

但这显然是行不通的,因为在找到单词之前,它会打印“wordnotfound”。好。。但我怎么能打印出找不到这个词?!我真的不知道。你知道吗

提前谢谢!你知道吗


Tags: pathininputrawdefwithlineword
3条回答
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")

作为一个额外的好处,它可以跟踪单词在文件中的第一个出现位置(如果有的话)。你知道吗

如果您只想打印是否在任何行中找到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')

Python有一个特殊的技巧:

for line in f:
    if word in line:
        print "Word found"
        break
else:
    print "Word not found"

这里的elsefor一起使用,如果循环正常完成而未命中break,则具体执行。你知道吗

相关问题 更多 >