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()
Member Avatar for masterofpuppets

try something like this for the file input:

fileName = raw_input( "Enter filename( include .txt ): " )
text = open( fileName, "r" )
wordCount = 0

for t in text.readlines():   
     wordsInLine = t.split( " " )
     wordCount += len( wordsInLine )
 
print "Word count is " + wordCount 
text.close()

This is in case the text in the file is correctly formated, i.e 1 space btw words..... :)

Thanks a bunch for that. It all makes sense now.

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
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.