编写一个名为file_stats的函数,该函数接受一个字符串参数(in_file),该参数是现有文本文件的名称。函数file_stats应该计算关于in_file的三个统计信息:包含的行数、字数和字符数,并将这三个统计信息打印在单独的行上。例如,以下内容将是正确的输入和输出。(提示:字符的数量可能因您正在工作的平台而异。) file_stats('created_equal.txt')行2字13个字符72个
以下是我所拥有的:
fileName = "C:\Users\Jeff Hardy\Desktop\index.txt"
chars = 0
words = 0
lines = 0
def file_stats(in_file):
global lines, words, chars
with open(in_file, 'r') as fd:
for line in fd:
lines += 1
wordsList = line.split()
words += len(wordsList)
for word in wordsList:
chars += len(word)
file_stats(fileName)
print("Number of lines: {0}".format(lines))
print("Number of words: {0}".format(words))
print("Number of chars: {0}".format(chars))代码给出了以下错误:
(unicode错误)‘独角形转义’编解码器无法解码位置2-3的字节:截断\UXXXXXXXX转义
发布于 2018-03-26 01:58:25
我相信你的错误与文件的编码有关,
或needs to be fileName = "C:\\Users\\Jeff Hardy\\Desktop\\index.txt"
指令要求您在函数中打印,不影响全局变量,然后需要更新循环中的值,而不是在它之后更新(缩进问题)。
def file_stats(in_file):
lines = words = chars = 0
with open(in_file, 'r', encoding="utf-8") as fd:
for line in fd:
lines += 1
words += len(line.split()) # If you split "x , y" is the comma a word?
chars += len(line) # Are spaces considered a character?
print("lines {0}".format(lines))
print("words {0}".format(words))
print("characters {0}".format(chards))https://stackoverflow.com/questions/49482850
复制相似问题