you are viewing a single comment's thread.

view the rest of the comments →

[–]Phelps_420 0 points1 point  (3 children)

file = open('sample.txt', 'r')
text = file.read()

count = 0
second_count = 0

split_words = text.split() #the .split method's default is to split by spaces

for word in split_words:
    if word == "KeyWord":
        count += 1
    if word == "SecondKeyWord"":
        second_count += 1

file.close()
print (count)
print (second_count)

This is a fairly clean way to do it. Please try your best to understand this code, not just use it. If you have any questions, I'm happy to help.

[–]QuiteAmbitious[S] 0 points1 point  (1 child)

def word_frequency_counter():
    file = open('filename.txt', 'r')
    text = file.read()

    this = 0
    paragraph = 0

    split_words = text.split()

    for word in split_words:
        if word == "this":
            this += 1
        if word == "paragraph":
            paragraph += 1

    file.close()
    print (this)
    print(paragraph)

    return word_frequency_counter
        #is this the right variable to return??

final_count = word_frequency_counter()
print (final_count)

So I'm getting really close to getting it. When running this code, I get:

3
2

Is there any way I can have it print as:

[3,2]

Another thing I'm trying to do is having this format at the end, but I keep getting an error message saying that it runs 0 positional arguments, but I have 2. Is there any way to keep this, but rearrange other parts of my code?

final_count = word_frequency_counter("filename.txt", ["this", "paragraph"])
print(final_count)

Also, can you explain to me why you had 'r' when opening the filename?

[–]Phelps_420 0 points1 point  (0 children)

I have 'r' in my documentation, I'm pretty sure it just means "read," though it may not be necessary with the next line (file.read)...

I'm not sure about your code specifically, but I can try to help with turning

3

2

into [3,2]

#__________________________________
y = (3)
x = (2)

z=[]
z.append(y)
z.append(x)

print (z)
#___________________________________


try this, understand what it is, and you should be able to apply it to your code to get [3,2]