Au cours du processus de développement, il est souvent nécessaire de déterminer si un mot-clé spécifié ou un mot d'exclusion existe dans une chaîne. Si plusieurs mots-clés sont définis, le jugement est souvent effectué par concaténation et conditions ou à l'aide d'une boucle for. Existe-t-il une méthode plus élégante ?
Déterminer si une chaîne contient une certaine chaîne
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
Déterminer si une chaîne contient l'une des plusieurs chaînes
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
Déterminer si une chaîne contient plusieurs chaînes
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
Comptez le nombre de fois qu'une chaîne contient la chaîne spécifiée
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