我需要创建一个程序来读取文本文件并计算行数、单词数和字符数。如果单独分开,我可以在下面完成所有工作,但我想将其转换为使用函数,以便它可以读取一次文件,但我不断得到不同的答案并且不确定我做错了什么。
字码
print ' '
fname = "question2.txt"
infile = open ( fname, 'r' )
fcontents = infile.read()
words = fcontents.split()
cwords = len(words)
print "Words: ",cwords
字符代码
fname = "question2.txt"
infile = open ( fname, 'r' )
fcontents = infile.read()
char = len(fcontents)
print "Characters: ", char
行代码
fname = "question2.txt"
infile = open ( fname, 'r' )
fcontents = infile.readlines()
lines = len(fcontents)
print "Lines: ", lines
正确的结果
字数:87 字数:
559
行数:12
这是我在尝试使用函数时想到的,但就是不知道出了什么问题。
def filereader():
fname = 'question2.txt'
infile = open ( fname, 'r' )
fcontents = infile.read()
fcontents2 = infile.readlines()
return fname, infile, fcontents, fcontents2
def wordcount(fcontents):
words = fcontents.split(fcontents)
cwords = len(words)
return cwords
def charcount(fcontents):
char = len(fcontents)
return char
def linecount(fcontents2):
lines = len(fcontents2)
return lines
def main():
print "Words: ", wordcount ('cwords')
print "Character: ", charcount ('char')
print "Lines: ", linecount ('lines')
main()
错误的结果
字数:2 字数:
4
行数:5