简体   繁体   English

如何判断是否在较大的字符串中找到了字符串列表?

[英]How do I tell if a list of strings are found within a larger string?

I have a list of words (ie): 我有一个单词列表(即):

['bad', 'good', 'smart']

that I need to find which lines in a file that contain all those words within that line. 我需要找到文件中哪些行包含该行中的所有这些单词。 I've tried: 我试过了:

for line in file_text: 
    if [w for w in list] in line:
        print(line) 

However I get the following error: 但是我收到以下错误:

TypeError: 'in <string>' requires string as left operand, not list

What is an easy pythonic way of doing this? 什么是简单的pythonic方法?

I think you want to use all (or any ): 我认为您想使用all (或any ):

>>> lst = ["the", "fox", "brown"]
>>> sentence = "the quick brown fox jumps over the lazy dog"
>>> all(word in sentence for word in lst)
True

One-Liner 一线

for line in file_text:
    [line for w in list if w in line and w == 'smart']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM