Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Homework help
#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


Messages In This Thread
Homework help - by RPC - Jun-16-2018, 06:00 AM
RE: Homework help - by RPC - Jun-16-2018, 11:06 AM
RE: Homework help - by buran - Jun-16-2018, 11:34 AM
RE: Homework help - by DeaD_EyE - Jun-16-2018, 12:58 PM
RE: Homework help - by RPC - Jun-17-2018, 05:39 AM
Homework help - by buran - Jun-16-2018, 06:12 AM

Forum Jump:

User Panel Messages

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