【问题标题】:Calculating Statistics From File从文件计算统计数据
【发布时间】:2018-03-26 01:44:51
【问题描述】:

编写一个名为 file_stats 的函数,它接受一个字符串参数 (in_file),它是现有文本文件的名称。函数 file_stats 应该计算关于 in_file 的三个统计数据:它包含的行数、单词数和字符数,并将这三个统计数据打印在不同的行上。例如,以下将是正确的输入和输出。 (提示:字符数可能因您使用的平台而异。)

file_stats('created_equal.txt')

lines 2

words 13

characters 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 error) 'unicodeescape' 编解码器无法解码字节 位置 2-3:截断\UXXXXXXXXXX 转义

【问题讨论】:

  • fileName 这只是一个例子。该文件可以具有您想要的任何名称,文件中的内容也可以是您想要的任何名称。它没有指定。它只需要像问题中所说的那样计算统计数据。
  • 它给了我与 fileName 相同的错误
  • len(wordsList) 在您阅读完所有行后进行计算和求和。
  • 附注:never use unescaped backslashes in non-raw strings。你很幸运\i 恰好不是转义序列;不要指望其他道路的运气。
  • 最后,如果错误来自读取文件,我们无法在不知道文件中实际内容的情况下进行调试。举个随机的例子,如果它是 BOM 编码的 UTF-16,答案是将 , encoding='utf-16' 放在 open, 的末尾,但如果它完全不同,那么这个答案对你没有帮助。由于错误似乎来自前几个字节,因此只需执行with open(in_file, 'rb') as f: print(f.read(80)) 之类的操作(注意'rb' 模式)并向我们展示输出可能就足够了。

标签: python python-3.x


【解决方案1】:

我相信您的错误与文件的编码有关,

needs to befileName = "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))

【讨论】:

    猜你喜欢
    • 2011-02-08
    • 2023-03-22
    • 1970-01-01
    • 1970-01-01
    • 2016-03-24
    • 2013-01-26
    • 1970-01-01
    • 2015-04-15
    相关资源
    最近更新 更多