对于我的 python 类,我被指示创建一个函数,该函数将读取文件并报告行数、单词数和字符数。我可以让代码工作,但是一旦我尝试将其转换为函数,它就不起作用了。怎么了?我还需要返回元组中的值。我不断收到此错误:UnboundLocalError: local variable 'line_cnt' referenced before assignment
def file_elem(filenm):
f = open(filenm,'r')
wrd_cnt = 0
char_cnt = 0
line_len = 0
while f is open:
line_cnt = len(f.readlines( ))
for line in f:
f_lines = line.split()
wrd_cnt += len(f_lines)
no_spaces = ''.join(line.split())
char_cnt += len(no_spaces)
return print(line_cnt, wrd_cnt, char_cnt)
import os
x = os.path.join("C:", "\\temp", "practice4.txt")
file_elem(x)