Python Forum
[split] Homework help
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[split] Homework help
#1
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!"))
Reply
#2
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
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply
#3
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
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020