我正在尝试完成一个简单的字数统计程序,它可以跟踪连接文件中的单词,字符和行数。
# 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
现在,如果一切顺利,它应该打印文件中的行,字母和单词的总数,但我得到的是这条消息:
“单词+ = len(单词) TypeError:'int'对象不可迭代 “
有什么问题?
解决了!新代码:
# 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
答案 0 :(得分:5)
您的计数似乎使用变量名称words
,而l.split()
的结果也是如此。您需要通过为它们使用不同的变量名来区分它们。