I need to prompt a user to type in a text file name and then take that file and and count the amount of words in the file. I have this code which counts the words in a file(that may not be "perfectly" written). I cannot figure out how to take the prompt text file and and get those words counted. I add a first line of say text = raw_input("enter a text file name: ") but I cannot take the file name given and have the words counted.
text = open("rainfall.txt", "r")
for t in text:
words = t.split()
wordCount = len(words)
print wordCount
text.close()
You are close:
fname = raw_input("enter a text file name: ")
fread = open(fname, "r")
# read the whole file into one string
text = fread.read()
fread.close()
# split the whole text string into words at "white-spaces"
word_list = text.split()
word_count = len(word_list)
print word_count
Last edited by bumsfeld; Oct 12th, 2009 at 3:48 pm.
Reputation Points: 404
Solved Threads: 180
Nearly a Posting Virtuoso
Offline 1,422 posts
since Jul 2005