Actually, there are two things that you’re not aware of,
The Return causes the function to return (stop the execution) right after that line, and there is a detail that is escaping you, the commas of the words, which make the check does not return true, ex: 'nos' == 'nos,' = False
.
Your code is corrected:
from collections import Counter
def popularidade (texto, palavras):
texto = texto.lower().split()
palavras = palavras.lower().replace(',', '').split() # tirar virgulas
lista = []
for p in palavras:
for t in texto:
if p == t:
lista.append(t)
return Counter(lista) # return quando todas as palavras verificadas
print(popularidade("Ao nos resolver a esta tarefa, preste nos atenção nos seguintes a nos pontos:", "nos a preste"))
DEMONSTRATION
To tell you the truth you don’t need 'so much happening' or Counter()
:
palavras = "nos, a, preste"
texto = "Ao nos resolver a esta tarefa, preste nos atenção nos seguintes a nos pontos:"
palavras_spl = palavras.lower().replace(',', '').split()
text_spl = texto.lower().split()
count = {p: text_spl.count(p) for p in palavras_spl if p in text_spl}
print(count) # {'preste': 1, 'a': 2, 'nos': 4}
DEMONSTRATION
Sequisers completely remove the punctuation of both, so as to ensure that both are left with only words:
import string
palavras = "nos, a, preste"
texto = "Ao nos resolver a esta tarefa, preste nos atenção nos seguintes a nos pontos:"
palavras_spl = palavras.translate(palavras.maketrans('','',string.punctuation)).lower().split()
text_spl = texto.translate(texto.maketrans('','',string.punctuation)).lower().split()
count = {p: text_spl.count(p) for p in palavras_spl if p in text_spl}
print(count) # {'preste': 1, 'a': 2, 'nos': 4}
DEMONSTRATION
You are returning from the function always in the first word found. Try removing the return from within the repeat loop. To better understand what your code does, take the table test.
– Woss