I need to write a program called wc.py. It promts the user to input a filename and outputs the number of lines, words, and, characters in the file. I really need help on this because I don't know what to do. email me at briggsie2006@ho tmail.com asap if you can help me out.
i need help asap
Collapse
X
-
Tags: None
-
Code:### We'll use Tk to make a window with a button so that we can get ### a file dialog box. You can add some place to display the results. It's ### probably a lot for starting out, but seeing this stuff now will ### give you a big head start! import Tkinter as Tk import tkFileDialog ### Use tkFileDialog.askopenfilename() to get the file name ### because it's just too hard for people to type in file names def DoEverything(): # initialize some variable for your counters nLines = 0 nWords = 0 # get the file name fileName = tkFileDialog.askopenfilename() # Once you have the name, call built-in open(); 'r' is for read mode. theFileObject = open(fileName, 'r') # File objects are of a class that support itteration, so you use a for loop # to get a string object which is a copy of the line in the file # I always call this variable 'line' for line in theFileObject: nLines += 1 # add one to the counter each time through the loop listOfWords = line.split() # string objects have lots of "methods" print listOfWords # Use print to see what your program is doing wordCount = len(listOfWords) # Use extra variable to simplify your code print wordCount nWords += wordCount # Add this lines word count to nWords # There are simpler ways to print, but format strings are a really good thing to learn print "%s has %d lines and %d words" %(fileName, nLines, nWords) # although Python will close the file if you forget, it's always good to remember theFileObject.close() if __name__ == "__main__": ### This is all it takes to start a Graphical User Interface with Tkinter! root = Tk.Tk() mainFrame = Tk.Frame(root) mainFrame.pack() fdButton = Tk.Button(mainFrame, text="File Dialog", command=DoEverything) fdButton.pack() root.mainloop() -
-
-
Here's a big hint:Originally posted by briggsie2006what about characters?
You'll need one more counter variable
Use a for loop inside the main loop
list objects (in this case listOfWords) are itterators, so use
I'll bet you get it!Code:for item in listOfWords: # use len() to count characters # accumulate total count
Post what you come up with...Comment
Comment