我正在尝试完成一个简单的字数统计程序,它可以跟踪连接文件中的字数、字符数和行数。
# This program counts the number of lines, words, and characters in a file, entered by the user.
# The file is test text from a standard lorem ipsum generator.
import string
def wc():
# Sets the count of normal lines, words, and characters to 0 for proper iterative operation.
lines = 0
words = 0
chars = 0
print("This program will count the number of lines, words, and characters in a file.")
# Stores a variable as a string for more graceful coding and no errors experienced previously.
filename =("test.txt")
# Opens file and stores it as new variable, and loops through each line once the connection with file is made.
with open(filename, 'r') as fileObject:
for l in fileObject:
# Splits text file into each individual word for word count.
words = l.split()
lines += 1
words += len(words)
chars += len(l)
print("Lines:", lines)
print("Words:", words)
print("Characters:", chars)
wc()
while 1:
pass
现在,如果一切顺利,它应该打印文件中的行数、字母和单词的总数,但我得到的只是这条消息:
“words += len(words) TypeError: 'int' object is not iterable”
怎么了?
解决了!新代码:
# This program counts the number of lines, words, and characters in a file, entered by the user.
# The file is test text from a standard lorem ipsum generator.
import string
def wc():
# Sets the count of normal lines, words, and characters to 0 for proper iterative operation.
lines = 0
words = 0
chars = 0
print("This program will count the number of lines, words, and characters in a file.")
# Stores a variable as a string for more graceful coding and no errors experienced previously.
filename =("test.txt")
# Opens file and stores it as new variable, and loops through each line once the connection with file is made.
with open(filename, 'r') as fileObject:
for l in fileObject:
# Splits text file into each individual word for word count.
wordsFind = l.split()
lines += 1
words += len(wordsFind)
chars += len(l)
print("Lines:", lines)
print("Words:", words)
print("Characters:", chars)
wc()
while 1:
pass