Durante o processo de desenvolvimento, muitas vezes é necessário determinar se uma palavra-chave especificada ou palavra de exclusão existe em uma string. Se várias palavras-chave forem definidas, o julgamento geralmente é feito concatenando condições e ou usando um loop for. Existe um método mais elegante ?
Determinar se uma string contém uma determinada string
p = "Tom is a boy,Lucy is a girl,they all like english!"
w= 'Tom'
print w in p
>>>True
print p.find(w) > -1
>>>True
Determinar se uma string contém qualquer uma das múltiplas strings
p = "Tom is a boy,Lucy is a girl,they all like english!"
keywords= 'Tom,Lucy'
excludes = ['english','math']
print any([w in p and w for w in keywords.split(',')])
>>>True
print any(e in p for e in excludes)
>>>True
Determinar se uma string contém várias strings
p = "Tom is a boy,Lucy is a girl,they all like english!"
keywords= 'Tom,Lucy'
filters= ["boy","like"]
print all(f in p for f in filters)
>>>True
print all([w in p and w for w in keywords.split(',')])
>>>True
Conte o número de vezes que uma string contém a string especificada
p = "Tom is a boy,Lucy is a girl,Tom like math and Lucy like english!"
keywords= 'english,math,history,laws'
print sum([1 if w in p and w else 0 for w in keywords.split(',')])
>>>2