我必须编写一个函数file_stats
,该函数以文件名作为参数,并返回一个包含三个数字的元组:行数,单词数和文件中的字符数>
我写了一个代码,该代码未通过单元测试。但是输出很好。如何通过单元测试?
num_lines = 0
num_words = 0
num_chars = 0
def file_stats(filename):
global num_lines, num_words, num_chars
with open(filename, 'r') as file:
for line in file:
words = line.split()
num_lines += 1
num_words += len(words)
num_chars += len(line)
tuple1 = (num_lines, num_words, num_chars)
file.close()
return tuple1
SampleFile.txt
LIET
Now, by Saint Peter's Church and Peter too,
He shall not make me there a joyful bride.
I wonder at this haste; that I must wed
Ere he, that should be husband, comes to woo.
I pray you, tell my lord and father, madam,
I will not marry yet; and, when I do, I swear,
It sh
预期产量-(9,58,304)
答案 0 :(得分:0)
global num_lines, num_words, num_chars
您正在使用全局变量。如果单元测试工具重复调用您的函数,则这些变量将仅初始化一次,从而产生错误的结果。
改为将代码更改为此:
def file_stats(filename):
num_lines, num_words, num_chars = (0,0,0)
with open(filename, 'r') as file:
for line in file:
words = line.split()
num_lines += 1
num_words += len(words)
num_chars += len(line)
return (num_lines, num_words, num_chars)
您不需要手动关闭文件,上下文管理器(with open(...) as file
)会为您完成