tom tom - 1 year ago 58
Python Question

Hi im trying to count how may words i I have in my file, but it keeps saying text 1 is not defined even though it is printed above

my code is trying to count how many words I have in the file which is printed above, after I wish to be able to enter a word and for the code to tell me how many of that words there are in the text and the position of it.
2 seconds the code did not paste.

Will not let me post image so here is the code

import os


file = open('text1.txt','r')


count = 0

with open(text1, "rb") as fp:

data = data.translate(string>maketrans("",""), string.punctuation)

for word in data.split():

if word in input_list:

count += 1


Answer Source

First thing wrong about your code, in os.path.isfile('text1.txt') you're testing whether the file text1.txt exists. Therefore, the return value will be either True or False and not putting it within a condition is completely unnecessary and unreasonable.

Ok, now for why your code is printing correctly but not counting words. It is because the first time you open the file (text1.txt) you open it correctly, but on the second time you as open to open the file from the variable text1 and as far as I can see, by the code you provided, there's no such variable. So the correct way would be something like this:

# pass string instead of variable
with open('text1.txt', "r") as fp:  # use only "r" as 'b' is for binary and it's a text file
    data = data.translate(string.maketrans("",""), string.punctuation)
    for word in data.split():
        if word in input_list:
            count += 1

Well, additionally, I don't know where this data.translate came from so I can't tell if it's interfering (I don't even know if it works - it didn't work for me).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download