Python Forum

Full Version: Need help implementing an input with file operations
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello Guys,

I am stuck on an assignment. I have done most of the work but the third step is giving me problem. So the third step is suppose to find a twitter handle or (username) with @, so it can be @anyone, any@ or @any@any@. It is suppose to report how much occurrences it finds when I type in the handle for ex. @spacex.

My problem is my output is not matching with the expected output.

Here's my code (relevant parts):

def cleanedup(s):
    alphabet = "abcdefghijklmnopqrstuvwxyz@"
    cleantext = ""
    s = s.replace("?s", "")
    s = s.replace("'s", "")
    for character in s.lower():
        if character in alphabet:
            cleantext += character
        else:
            cleantext += ""
   return cleantext

dictionary = {}
with open("elon-musk.txt") as file:
    for tweet in file:
        for word in tweet.lower().split():
            word = cleanedup(word)
            if "@" in word:
                if word in dictionary.keys():
                    dictionary[word] += 1
                else:
                    dictionary[word] = 1

while True:
    username = input("Enter username: ")
    if username in dictionary:
        print("Mentioned", (dictionary[username]), "times.")
    else:
        print("Not found")
Output should be:

Quote:Enter username: @spacex
Mentioned 187 times.
Enter username: @nasa
Mentioned 41 times.

I get:

Quote:Enter username: @spacex
Mentioned 187 times.
Enter username: @nasa
Mentioned 40 times.

So my question is what is wrong with my code that its skipping over the last mention for @nasa? Also Is there any simpler way of doing this? Without s.replace()? I need to get it as simple since that is my assignment constraints.

elon-musk.txt
what is the purpose of lines 4 and 5?
Are you expecting "?s" or "'s" in the incoming string, and if so, why remove them.
Please post the complete assignment, verbatim.
Look for nasa in the text. One occurrance will be different from the others.
(Jun-08-2022, 11:08 AM)Larz60+ Wrote: [ -> ]what is the purpose of lines 4 and 5?
Are you expecting "?s" or "'s" in the incoming string, and if so, why remove them.
Please post the complete assignment, verbatim.

Those were to sanitize the file because without them I get completely different answer for @spacex.
Full Assignment