By your description ("if I don’t find the word sulfite paper I do a new search only for paper"), would do so:
def busca_termo(termo, texto):
# primeiro vê se o termo está contido no texto
if termo in texto:
return True
# senão, procura apenas pela primeira palavra do termo dentro do texto
return termo.split(maxsplit=1)[0] in texto
produtos = ['papel A4', 'caderno', 'papel sulfite', 'sulfite']
termo = 'papel sulfite'
results = [ p for p in produtos if busca_termo(termo, p) ]
print(results) # ['papel A4', 'papel sulfite']
How are you using find
, understood that the term can be in any position of the string (ie, termo
must be a substring of texto
). Since you don’t seem to need the index (and just want to know if it’s substring or not), the documentation itself recommends using the operator in
instead of find
.
In the above example, if the term is "sulfite paper", I first check whether the whole term is contained in the text. Otherwise, I look only if "paper" is contained in the text.
I understood that you do not need to search for "sulfite", but if you want to search for all the words of the term, just change the function busca_termo
for:
def busca_termo(termo, texto):
# primeiro vê se o termo está contido no texto
if termo in texto:
return True
# verifca se tem alguma palavra do termo que está contida no texto
return any(palavra for palavra in termo.split() if palavra in texto)
produtos = ['papel A4', 'caderno', 'papel sulfite', 'sulfite']
termo = 'papel sulfite'
results = [ p for p in produtos if busca_termo(termo, p) ]
print(results) # ['papel A4', 'papel sulfite', 'sulfite']
Now he searches first for "sulfite paper", and if he does not find it, he searches separately for "paper" and "sulfite" (returning True
find any of them).
Why don’t you write a function
busca_termo(termo, texto) -> bool
which makes all the validations it needs and in the expression makes[t for t in buscaprodutos if busca_termo(termo, t.NM_PRODUTO)]
. If your function returns True, the element will be in the final list.– Woss
@Woss, knows how to break the string into parts and make type if text.find(paper') and if text.find('sulfite') dynamically ?
– Marco Souza