Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Homework help
#1
Hello everyone Heart

I have just started a new course in python, and i do not normally ask for help until i find myself against the wall Wall . I am just struggling with a homework, and for some of you it may be easy but, I just cannot figure out how to solve it.

I have to develop a function in python that return the frequency of each word in the string, the function has to convert all words low case and eliminate punctuations:
1. receive as input a string
2. It has to return a dictionary with the following details:

*covert every word in the string into lowercase
*delete all punctuation

Example:


text="hello my friend, are you my friend? I need some help, hello? hello?"


Should return:

{"hello":3,"my":1,"friend":2,"are":1,"I":1,"need":1,"some":1"help":1}

As you can see there is no punctuation,and since the dictionaries has not an order the order of the words can change.

I really need some help Pray It would be very nice if you could help me i have been trying to solve it for 3 days so far, and have t deliver it for this Sunday.
Cry Cry

I will continue trying meanwhile.

Note: I can use
world.split()
word=word.lower()
x.isalpha()
Reply
#2
Please, post your best attempt so far in python tags. If you get any errors post the full traceback in error tags.
We are glad to help, but will not do it for you.
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
#3
Hello, for sure , i am not asking you to solve my homework, i am sorry i there was a misunderstood Doh

Here is what I have done until now, but the problem is that if one word in my string is next to a punctuation, it does not count it in my dictionary, but if i eliminate the isalphait counts the punctuations.

I need to figure out how can I eliminate a punctuation from an element in my list. Here is my function until now:



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           
        #Here i plain to make an exception with ELSE ,but i need to understant first how to eliminate punctuation 
        #from my string and count it in my dictionary.
            
    return(Dict)
Here I call my function as a example:
cadena="Hola que haces? Por favor respondeme, di hola por lo menos!"
print(myfunction(cadena))
And this is what a I get:

{'hola': 2, 'que': 1, 'por': 2, 'favor': 1, 'di': 1, 'lo': 1}

I ask you python lovers for help Pray
Reply
#4
if isalpha() returns False, the word has a punctuation in it. you can use slicing to remove the last char (assuming it is a punctuation) before adding to dict
>>> myword = 'hello'
>>> myword.isalpha()
True
>>> myword='hello?'
>>> myword.isalpha()
False
>>> myword[:-1]
'hello'
now, this doesn't solve complex cases like self-made in which isalpha() will return False
As an alternative


You can check, that last char i.e. myword[-1].isalpha() is False and remove it.
>>> myword='hello?'
>>> myword[-1].isalpha()
False
>>> myword[:-1]
'hello'
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
#5
EDIT: Don't read my post, if you are only allowed to use the primitives.



You can use punctuation from strings module.
Then you can iterate over the string and look if the
char is not in the punctuation string and add it to
the result. The result is a list in the first and second example.
To convert a list with strings into one string, you can
use the str.join('', result) or
''.join(result).

from string import punctuation


def punctuation_filter1(text):
    """
    Naive implementation with a for loop and a list
    """
    result = []
    for char in text:
        if char not in punctuation:
            result.append(char)
    return ''.join(result)


def punctuation_filter2(text):
    """
    List Comprehension
    """
    result = [char for char in text if char not in punctuation]
    return ''.join(result)


def punctuation_filter3(text):
    """
    A generator expression inside a function call 
    """
    return ''.join(char for char in text if char not in punctuation)

print('Punctuation:', punctuation)
testtext = '!?.,Hello World!'
print('testtext:', testtext)
print('punctuation_filter1:', punctuation_filter1(testtext))
print('punctuation_filter2:', punctuation_filter1(testtext))
print('punctuation_filter3:', punctuation_filter1(testtext))
Now back to your original problem.
The teacher want that you understand the algorithm.
We want, that you understand Python.

When you have some kind of a collection,
you can count the occurrence of unique elements with Counter from collections module.

from collections import Counter
words = "hello my friend, are you my friend? I need some help, hello? hello?"
# first filtering punctuation, then lower case, then split
clean_word_list = punctuation_filter3(words).lower().split()

result = Counter(clean_word_list)
print(result.most_common())
Another older solution is with defaultdict.

from collections import defaultdict

counter = defaultdict(int)
for word in clean_word_list:
    counter[word] += 1
print(counter)
A defaultdict has a default factory for missing keys,
which is in this case int. Calling int() returns 0.
If you access a key, which does not exist it returns a 0.
With the first occurrence of a word, which is not as a key in the dict, 0 is returned.
This is the cause, why the inline addition works.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#6
Hello everyone,

I read all your posts until now, I had a busy day at work. But I could wait any longer to try out the new code.
I really appreciate your time and kindness, and yes I thank you that you really help me to understand real Python.

I already finished my coding thanks to your help, I took a line from both codes to improve mine. I will definitely look for a python book.

Thank you again, when my assignment is graded i will upload my final code .
Reply


Forum Jump:

User Panel Messages

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