在这种情况下调用的是什么(在文档中通过其名称找到它)

问题描述 投票:0回答:2

我想检查文本文件中是否有一些单词,但我需要使搜索不区分大小写,因此,我需要知道if条件中的“in”是如何工作的,并查看其文档中的选项如此。

但我通过搜索谷歌找不到它,我试图使用像“条件语句python”这样的术语搜索,但仍然找不到它。

#!/usr/bin/python3

search_words = ['Day 3','day 3']

with open('test-target.txt','r') as targetFile:
    for search_word in search_words:

        if search_word in targetFile.read():
            print('yes')
        else:
            print('no')

        # put the read cursor again at the begining of the file to prepare it fot next read ^o^
        targetFile.seek(0)

文件:

Day 3 Lab ......etc
bla bla bla

输出:

yes
no
python if-statement search condition
2个回答
1
投票

您可以使用casefold()进行不区分大小写的搜索。您不需要使用seek(0)作为文件指针,默认情况下,当您打开它时指向文件的开头。如果您对耗尽文件指针感到困扰,请将文件内容读取到变量,并在循环中使用该变量:

with open('test-target.txt','r') as targetFile:
    file_contents = targetFile.read()
    for search_word in search_words:
        if search_word.casefold() in file_contents:
            print('yes')
        else:
            print('no')

0
投票

这被称为“包含”运算符,membership test operator。它没有真正的选择;它只是检查某些东西是否存在于其他东西中 - 但你可以“规范化”这些“某些东西”,例如在检查收容之前,将两者转换为小写(或大写,或Unicode normalized case folded或适用于您的特定应用的任何内容)。

但是,反复寻找文件是非常低效的。您想要将文件读入内存一次:

# Normalize once, before looping
search_words = set([x.lower() for x in ['Day 3','day 3']])

with open('test-target.txt','r') as targetFile:
    contents = targetFile.read()
for search_word in search_words:
    if search_word in contents.lower():
        print('yes')
    else:
        print('no')

......或者一次检查一条线:

with open('test-target.txt','r') as targetFile:
    for line in targetFile:
        for search_word in search_words:
            if search_word in line.lower():
                print('yes')
                break # maybe?
    else:
        print('no')

这将更加健壮,因为您可以处理任意大的文件,只要每条线都适合内存。

请注意for循环如何通过by具有else分支。

作为可用性改进,您打印的消息可能应该标识每次迭代中找到或未找到的搜索词。

© www.soinside.com 2019 - 2024. All rights reserved.