在Python中,在文本文件中搜索多个单词并打印相应的行

时间:2018-07-12 05:18:53

标签: python string list file search

我有一个要搜索的句子列表。我要打印包含搜索词的行。这段代码有效:

fruit_list = open('fruitlist.txt')
for line in fruit_list:
    if 'apple' in line or 'banana' in line or 'orange' in line:
        print (line)

但是这可能非常乏味。特别是如果我希望我的搜索词列表更长。我想列出搜索词,并使用它来搜索文档并打印行。

search_words=['apple','banana','orange','lemon']
for line in fruit_list:
    if item in search_words in line:
        print (line)

此代码不起作用,因为未定义“项目”。无论如何,我可以做到这一点?我是python的新手。

2 个答案:

答案 0 :(得分:3)

尝试一下:

fruit_list = open('fruitlist.txt')

search_words = ['apple', 'banana', 'orange', 'lemon']

for line in fruit_list:
    if any(word in line for word in search_words):
        print(line)

答案 1 :(得分:0)

Select '1/1/2014' as date1, 
TO_DATE (
case   
    when strtok(date1, '/', 1) between 1 and 9  and strtok(date1, '/', 2) between 1 and 9 then strtok(date1,'/', 3)||'/0'||strtok(date1, '/', 1)||'/0'||strtok(date1,'/', 2)
    when strtok(date1, '/', 1) between 1 and 9  and strtok(date1, '/', 2) > 9 then strtok(date1,'/', 3)||'/0'||strtok(date1, '/', 1)||'/'||strtok(date1,'/', 2)
    when strtok(date1, '/', 1) > 9 and strtok(date1, '/', 2) between 1 and 9  then strtok(date1,'/', 3)||'/'||strtok(date1, '/', 1)||'/0'||strtok(date1,'/', 2)
    else  strtok(date1, '/', 3)||'/'||strtok(date1, '/', 1)||'/'||strtok(date1,'/', 2)
end , 'YYYY/MM/DD') as req_date