Python Forum

Full Version: [split] Homework help
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi Buran

I am having a similar issue to the above.
The below is my code, but my dictionary isn't including the word which has punctuation in at all, I attempted to follow your advice but no success, any more hints?

def myfunction(cadena):
    
    texto=cadena
    x=texto.lower().split()
    Dict={}
    
    for element in x:
        if element.isalpha():
                if element in Dict:
                    Dict[element]+=1
                else:
                    Dict[element]=1
        else:
            element[:-1] 
    return(Dict)
    

print(myfunction("Hola que haces? Por favor respondeme, di hola por lo menos!"))
It's not good idea to use 'Dict' as variable name. It's too similar to built-in 'dict'. This name also have no hint what dictionary it is. Maybe something along this - 'contar_palabras' (pardon my spanish :-))

If I understand correctly then your problem is that last words in sentence which have punctuation at end with no space are counted as different words. You should get rid of punctuation, either using your own punctuation list (like '!.?,:;"') or using string.punctuation
The particular problem - you need line 14 to be like this
Dict[element[:-1]] += 1
Note that if element[:-1] is not in the dict this will raise error. I will leave to you to fix this yourself