Reputation: 651
This is what I have (which includes extra processing):
import string
def main():
fileInput = open("A tisket a tasket.txt",'r')
characters, words, lines = countEmUp(fileInput)
printCounts(characters, words, lines)
tokenList = splitToTokens(fileInput)
print(tokenList)
def countEmUp(someFileInput):
lines, words, chars = 0, 0, 0
for line in someFileInput:
chars += len(line) # using += for nice and concise updates
words += len(line.split())
lines += 1
return chars, words, lines
def printCounts(ch,wd,ln):
print("Your file contains the following:")
print("Characters:",ch)
print("Words:",wd)
print("Lines:",ln)
def splitToTokens(aFileInput):
tokenList = []
for line in aFileInput:
tokenList.extend(line.split())
return tokenList
main()
The problem starts at the splitToTokens function.
What I'm trying to do is create an empty list, iterate through a file I opened for reading line-by-line, and add the tokens in that line to my tokenList so I can process the tokens later.
When I print tokenList in my main() function it's still an empty list.
I suspect that maybe it has to do with my fileInput already being called? I'm trying not to open the file more than once.
Upvotes: 1
Views: 46
Reputation: 6556
You are trying to re-read file, you have to move the cursor to the beginning of the file:
file.seek(0)
change your code to:
import string
def main():
fileInput = open("A tisket a tasket.txt",'r')
characters, words, lines = countEmUp(fileInput)
fileInput.seek(0) #offset of 0
printCounts(characters, words, lines)
tokenList = splitToTokens(fileInput)
print(tokenList)
def countEmUp(someFileInput):
lines, words, chars = 0, 0, 0
for line in someFileInput:
chars += len(line) # using += for nice and concise updates
words += len(line.split())
lines += 1
return chars, words, lines
def printCounts(ch,wd,ln):
print("Your file contains the following:")
print("Characters:",ch)
print("Words:",wd)
print("Lines:",ln)
def splitToTokens(aFileInput):
tokenList = []
for line in aFileInput:
tokenList.extend(line.split())
return tokenList
main()
Upvotes: 4