#๐Ÿ”’ Hi everyone , anyone can help me about count words assignment , but from lab ?

162 messages ยท Page 1 of 1 (latest)

brittle osprey
#

Need help with Python assignment (word counter):

I need to write a program that counts how many times each word appears in a text file.

Weโ€™re given a function countFile(fname) that reads the file line by line and calls my function countWords(counts, line).

they provide function as following
def countFile(fname): counts={} with open(fname) as f: for line in f: countWords(counts,line) pass pass printResults(counts) pass

Tasks:

Implement countWords(counts, line)

Split each line into words

Update a dictionary that tracks word frequencies

Improve accuracy by:

Removing punctuation using strip('-?.!,[]โ€”:;"'')

Making all words lowercase using .lower()

Modify printResults() to print:

One word and its count per line (e.g. the : 72)

Sort the output alphabetically by word before printing.

If anyone can help with the logic or sample code, Iโ€™d really appreciate it ๐Ÿ™

muted sonnetBOT
#

@brittle osprey

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

little moth
#

what have you written / tried already?

fickle grove
#

show your code

brittle osprey
#

def countWords(counts, line):
# Step 1: Split line into words
words = line.split()

for word in words:
    # Step 2: Clean the word (lowercase and strip punctuation)
    clean_word = word.lower().strip('-?.!,[]โ€”:;"\'')
    
    # Only add if word is not empty
    if clean_word:
        if clean_word in counts:
            counts[clean_word] += 1
        else:
            counts[clean_word] = 1
return counts

def printResults(counts):
# Step 4: Convert dictionary to list of tuples
word_list = list(counts.items())

# Sort alphabetically by the word (which is index 0 of the tuple)
# The 'key' parameter is what the Step 4 instructions requested
word_list.sort(key=lambda item: item[0])

# Step 3: Print each word and its count
for word, count in word_list:
    print(f"{word} : {count}")

def countFile(fname):
counts = {}
with open(fname) as f:
for line in f:
countWords(counts, line)
# 'pass' was in your initial code; it doesn't hurt to leave it
pass
pass
printResults(counts)
pass

Run the program using your test file

countFile('test.txt')

muted sonnetBOT
#

Hey @brittle osprey!

Please edit your message to use a code block

```py
print('Hello, world!')
```

This will result in the following:

print('Hello, world!')```
fickle grove
#

use andpy

#
```py
#

aaa

#

use the back ticks

brittle osprey
#

can I call u ?

fickle grove
#

ummmm

#

after 5 mins

brittle osprey
#

ok , because this assignment is a little complex๐Ÿ˜…

fleet frigate
#

Can you explain which part you're having trouble with specifically?

fickle grove
little moth
#
def countWords(counts, line):
    # Step 1: Split line into words
    words = line.split()

    for word in words:
        # Step 2: Clean the word (lowercase and strip punctuation)
        clean_word = word.lower().strip('-?.!,[]โ€”:;"')

Only add if word is not empty
        if clean_word:
            if clean_word in counts:
                counts[clean_word] += 1
            else:
                counts[clean_word] = 1
    return counts

def printResults(counts):
    # Step 4: Convert dictionary to list of tuples
    word_list = list(counts.items())

Sort alphabetically by the word (which is index 0 of the tuple)
The 'key' parameter is what the Step 4 instructions requested
    word_list.sort(key=lambda item: item[0])

Step 3: Print each word and its count
    for word, count in word_list:
        print(f"{word} : {count}")

def countFile(fname):
    counts = {}
    with open(fname) as f:
        for line in f:
            countWords(counts, line)
            # 'pass' was in your initial code; it doesn't hurt to leave it
            pass
        pass
    printResults(counts)
    pass

Run the program using your test file
countFile('test.txt')
#

let's see

fleet frigate
#

the quotes in the strip string is messing with it

little moth
#

yeah

fleet frigate
#

@brittle osprey Did you run this code through chatGPT or something already?

little moth
#

fixed

#

this seems like chatGPT

brittle osprey
#

i have a file , this file is talking about instruction but I cant send it because over 2000 word

#

no i will try now

little moth
#

so the bold header steps are your instructions?

fleet frigate
little moth
#

# 'pass' was in your initial code; it doesn't hurt to leave it
what about this, this seems like an ai answer

brittle osprey
little moth
#

M, you have to be honest here or help will be very difficult

brittle osprey
#

These photo explain what should i do

#

I tried many of times

little moth
#

well at what part are you stuck?

#

it's split up into steps to make the overall task less scary

#

since you can focus on one step at a time and then end up with the final version

brittle osprey
#

I hope these photos make it sense and understandable

little moth
little moth
brittle osprey
#

This is a test file for word counting.
Caesar was a great leader. Caesar won many battles.
The word 'caesar' should appear multiple times.
Testing, testing, 1, 2, 3! Let's count words.
this is from text.txt to count

little moth
#

okay

#

M, have you tried to run the code ??

little moth
#

for example yes

brittle osprey
#

Just indentation,

little moth
#

well just add a comment

#

for only add if word is not empty

brittle osprey
#

No output appeared

little moth
#

well is that as expected?

#

does that code print anything?

brittle osprey
#

No

little moth
#

so it should not output anything to the console

#

which is ok

brittle osprey
#

Want to submit and see ?

little moth
#

well not so fast

craggy zinc
little moth
# brittle osprey Want to submit and see ?
def countWords(counts, line):
    # Step 1: Split line into words
    words = line.split()

    for word in words:
        # Step 2: Clean the word (lowercase and strip punctuation)
        clean_word = word.lower().strip('-?.!,[]โ€”:;"')

    # Only add if word is not empty
        if clean_word:
            if clean_word in counts:
                counts[clean_word] += 1
            else:
                counts[clean_word] = 1
    return counts

def printResults(counts):
    # Step 4: Convert dictionary to list of tuples
    word_list = list(counts.items())
#

they have also provided a fuction to print counts

#

so you can just run the code and see if it returns 34

brittle osprey
#

No output appeared

#

But I think u understand what is the instructions right?

little moth
#

well you also have to include the countFile code

#

and then do

def countFile(filename):
  ...
def countWords(counts, line):
  ...

def printResults(counts):
  ...
countFile("text.txt")
#

@brittle osprey

brittle osprey
#

Ok , can u give me the full code?

little moth
#

???

#

I don't have the countFile code

#

you have it

brittle osprey
little moth
#

No like ... is just whatever code follows

#

so make sure you have those 3 functions with all their code inside and then add the line

at the bottom

brittle osprey
#

def countWords(counts, line):
# Step 1: Split line into words
words = line.split()

for word in words:
    # Step 2: Clean the word (lowercase and strip punctuation)
    clean_word = word.lower().strip('-?.!,[]โ€”:;"')

# Only add if word is not empty
    if clean_word:
        if clean_word in counts:
            counts[clean_word] += 1
        else:
            counts[clean_word] = 1
return counts

def printResults(counts):
# Step 4: Convert dictionary to list of tuples
word_list = list(counts.items())

this is the code which u gave it to me , just can u tell where should add these fuctions here , thank u and appreciate ur help๐Ÿ™

little moth
#

You have to add the countFile function you got in the assigment details

compact wagon
#

!e
The reason for no output code, is that you have not called the function.

def greet():
  return "Hello PyDis"

Like this, the function is defined but its not being called

muted sonnetBOT
little moth
#

and then at the bottom do countFile("text.txt") to test it out

compact wagon
#

If you want the output, you have to call the function as what Martinus kept pointing it out

little moth
compact wagon
#

!e
A quick example of how to call the function

def greet():
  return "Hello PyDis"

print(greet())
little moth
#

Look, they provided the function

muted sonnetBOT
brittle osprey
little moth
#

to the file with the other two yes

#

then to try if everything works... run the function countFile by doing countFile("text.txt") at the bottom of the file

#

@brittle osprey , am I making sense?

brittle osprey
#

of course , thanks for ur time,

#

def countWords(counts, line):
# Step 1: Split line into words
words = line.split()

for word in words:
    # Step 2: Clean the word (lowercase and strip punctuation)
    clean_word = word.lower().strip('-?.!,[]โ€”:;"')

# Only add if word is not empty
    if clean_word:
        if clean_word in counts:
            counts[clean_word] += 1
        else:
            counts[clean_word] = 1
return counts

def printResults(counts):
# Step 4: Convert dictionary to list of tuples
word_list = list(counts.items())

def countFile(fname):
counts={}
with open(fname) as f:
for line in f:
countWords(counts,line)
pass
pass
printResults(counts)
pass

countFile("text.txt") this is my full code

little moth
#

yes that should work if you run it

#

well, it should test if your countWords is written correctly

#

!code

muted sonnetBOT
#
Formatting code on Discord

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

For long code samples, you can use our pastebin.

little moth
#

also try this in the future

brittle osprey
compact wagon
#

none of those functions have print tho pithink

little moth
#

oh true

compact wagon
little moth
#

okay where is text.txt located

#

ah right

brittle osprey
#

so...what must I do right now?

little moth
#

well, where is the text file located you want to test?

#

is it where the assigment says it is?

compact wagon
brittle osprey
compact wagon
#

what?

little moth
compact wagon
# brittle osprey

You could caesar.txt if you want. Not sure if thats the exact text file that Coursera provides

little moth
#

or that

#

python is trying to look for text.txt but there is no file with that name in your screenshot

#

so you choose one of the others to test

brittle osprey
#

do u mean rename this file?

little moth
#

no

#

change the code

#
countFile("text.txt")

if you do this, python is looking for the file text.txt

#

look at your screenshot, there is no file with that name

#

so... you provide another filename between "

#
countFile("test.txt")  

for example

#

or

countFile("hamlet.txt")  
brittle osprey
little moth
#

yes, that's progress

#

now...

#
def printResults(counts):
    # Step 4: Convert dictionary to list of tuples
    word_list = list(counts.items())
#

this function, it is named printResults, but does it print something?

brittle osprey
#

no...

little moth
#

so what would you have to add?

brittle osprey
#

def countWords(counts, line):
# Step 1: Split line into words
words = line.split()

for word in words:
    # Step 2: Clean the word (lowercase and strip punctuation)
    clean_word = word.lower().strip('-?.!,[]โ€”:;"')

# Only add if word is not empty
    if clean_word:
        if clean_word in counts:
            counts[clean_word] += 1
        else:
            counts[clean_word] = 1
return counts

def printResults(counts):
# Step 4: Convert dictionary to list of tuples
word_list = list(counts.items())

def countFile(fname):
counts={}
with open(fname) as f:
for line in f:
countWords(counts,line)
pass
pass
printResults(counts)
pass

countFile("hamlet.txt") this is my current code

little moth
#

This does not help

#

try to answer the question

brittle osprey
#

No ,
Submit the assignment to see the results?

#

I have many of attempts

little moth
#

I don't see how that will help

#

your code does not output anything

#

I want you to answer this simple question

#
def printResults(counts):
    # Step 4: Convert dictionary to list of tuples
    word_list = list(counts.items())

here word_list will be a list like [("and,", 5), ("ceasar,", 5), ("the,", 10)]

#

but if we run the code...

#

!e

def printResults():
    # Step 4: Convert dictionary to list of tuples
    word_list = [("and,", 5), ("ceasar,", 5), ("the,", 10)]

printResults()
muted sonnetBOT
little moth
#

it gives no output...

#

how can I see [("and,", 5), ("ceasar,", 5), ("the,", 10)] as the output???

#

@brittle osprey

#

if you don't bother to really think instead of copy pasting... I might be out

#

this is basic python, and you have like an assignment so it's good if you really understand it

brittle osprey
#

I got it how

#

I must write print(word_list)

little moth
#

yes

#

so

def printResults(counts):
    # Step 4: Convert dictionary to list of tuples
    word_list = list(counts.items())
    print(word_list)
#

and then run the program

brittle osprey
#

[('this', 1), ('is', 1), ('a', 2), ('test', 1), ('file', 1), ('for', 1), ('word', 2), ('counting', 1), ('caesar', 2), ('was', 1), ('great', 1), ('leader', 1), ('won', 1), ('many', 1), ('battles', 1), ('the', 1), ("'caesar'", 1), ('should', 1), ('appear', 1), ('multiple', 1), ('times', 1), ('testing', 2), ('1', 1), ('2', 1), ('3', 1), ("let's", 1), ('count', 1), ('words', 1)]

#

yeah , the output appeared

little moth
#

great

#

now test ceasar.txt

brittle osprey
#

done...

little moth
#

and?

brittle osprey
#

so should I submit right?

little moth
#

you can yea

muted sonnetBOT
#
Python help channel closed for inactivity

This help channel has been closed. Feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.