Accessing Each Word in a File


file = open(filePath, 'rU') for line in file:     for word in line.split():         wordList.append(word)

A useful tool when processing files is to separate each word in the file and process them one at a time. The words can be individually processed by opening the file, reading each line into a string, and then splitting the strings into words using the split() function.

The program read_words.py shows a simple example of reading a file and processing the words one at time. The lines in the file are processed one at a time using a for loop. The split() function splits the line into a list of words based on spaces because no other character was passed as the separator argument. Once the words are separated, they can be individually processed into lists, dictionaries, and so on.

filePath = "input.txt" wordList = [] wordCount = 0 #Read lines into a list file = open(filePath, 'rU') for line in file:     for word in line.split():         wordList.append(word)         wordCount += 1 print wordList print "Total words = %d" % wordCount


read_words.py

['Line', '1', 'Line', '2', 'Line', '3', 'Line', '4'] Total words = 8


Output from read_words.py code



Python Phrasebook(c) Essential Code and Commands
Python Phrasebook
ISBN: 0672329107
EAN: 2147483647
Year: N/A
Pages: 138
Authors: Brad Dayley

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net