【问题标题】:Not counting characters right in text file不计算文本文件中的字符
【发布时间】:2015-06-04 07:19:26
【问题描述】:

我正在使用文本文件 I/O 执行另一个程序,但我很困惑,因为我的代码看起来非常合理,但结果似乎很疯狂。我想计算政治演讲文本文件中的单词、字符、句子和唯一单词的数量。这是我的代码,所以它可能会澄清一些事情。

#This program will serve to analyze text files for the number of words in
#the text file, number of characters, sentances, unique words, and the longest
#word in the text file. This program will also provide the frequency of unique
#words. In particular, the text will be three political speeches which we will
#analyze, building on searching techniques in Python.
#CISC 101, Queen's University
#By Damian Connors; 10138187

def main():
    harper = readFile("Harper's Speech.txt")
    print(numCharacters(harper), "Characters.")
    obama1 = readFile("Obama's 2009 Speech.txt")
    print(numCharacters(obama1), "Characters.")
    obama2 = readFile("Obama's 2008 Speech.txt")
    print(numCharacters(obama1), "Characters.")

def readFile(filename):
    '''Function that reads a text file, then prints the name of file without
'.txt'. The fuction returns the read file for main() to call, and print's
the file's name so the user knows which file is read'''
    inFile1 = open(filename, "r")
    fileContentsList = inFile1.readlines()
    inFile1.close()
    print(filename.replace(".txt", "") + ":")  #this prints filename
    return fileContentsList

def numCharacters(file):
    return len(file) - file.count(" ")

我目前遇到的问题是计算字符数。它一直说# 是 85,但它是一个相当大的文件,我知道它应该是 7792 个字符。知道我在做什么错吗?这是我的 shell 输出,我使用的是 python 3.3.3

>>> ================================ RESTART ================================
>>> 
Harper's Speech:
85 Characters.
Obama's 2009 Speech:
67 Characters.
Obama's 2008 Speech:
67 Characters.
>>> 

如您所见,我有 3 个语音文件,但它们不可能是这么少的字符。

【问题讨论】:

  • 小故障是您使用的是obama1,即使您期望obama2 结果也是如此。
  • fileContentsList 文件中有行。不是字符。所以len(file) 返回文件中的行数
  • 下面的答案应该可以解决它。尝试创建一个小而简单的文件,您知道输出应该是什么,并尝试打印变量,以检查它是否符合您的预期。

标签: python file python-3.x io count


【解决方案1】:

您应该更改此行fileContentsList = inFile1.readlines() 现在你在数奥巴马在他的演讲中有多少行。 将 readLines 改为 read() 就可以了

【讨论】:

  • 对于您的其他评论,这就是您可以从字符串中删除所有数字的方法result = ''.join([i for i in your_string if not i.isdigit()])@DamianConnors
【解决方案2】:

readlines 函数返回一个包含的列表,因此它的长度将是文件中的行数,不是字符数。

您要么必须找到一种方法来读取所有字符(以便长度正确),例如使用read()

或者遍历每一行来统计其中的字符,可能是这样的:

tot = 0
for line in file:
    tot = tot + len(line) - line.count(" ")
return tot

(当然,假设您选择的计算字符的实际方法是正确的)。


顺便说一句,您的第三个输出语句引用了obama1 而不是obama2,您可能也想解决这个问题。

【讨论】:

  • 谢谢你,很棒的答案,我很高兴你也向我解释了,现在我知道未来的编码了。
  • 我在数单词方面也遇到了麻烦。我需要知道如何删除所有数字字符...我正在寻找一种简单的方法来执行此操作,我的文件有 1361 个单词(harper),这会将所有连字符、双空格、\n 全部切换为空格,然后使用 split 来计算空格...我已经这样做了,但我还需要删除所有数字。
【解决方案3】:

您正在计算行数。更详细地说,您正在有效地将文件读入行列表,然后对它们进行计数。下面是代码的清理版本。

def count_lines(filename):
    with open(filename) as stream:
        return len(stream.readlines())

对此类代码进行计数的最简单更改是读出整个文件并将其拆分为单词,然后对其进行计数,请参见以下代码。

def count_words(filename):
    with open(filename) as stream:
        return len(stream.read().split())

注意事项:

  • 可能需要更新代码以匹配您对单词的确切定义。
  • 此方法不适用于非常大的文件,因为它将整个文件读入内存,单词列表也存储在那里。

因此,上述代码更像是一个概念模型,而不是最佳最终解决方案。

【讨论】:

    【解决方案4】:

    您当前看到的是文件中的行数。由于 fileContentsList 将返回一个列表,numCharacters 将返回列表的大小。

    如果你想继续使用'readlines',你需要统计每行的字符数并将它们相加得到文件中的总字符数。

    def main():
        print(readFile("Harper's Speech.txt"), "Characters.")
        print(readFile("Obama's 2009 Speech.txt"), "Characters.")
        print(readFile("Obama's 2008 Speech.txt"), "Characters.")
    
    def readFile(filename):
        '''Function that reads a text file, then prints the name of file without
    '.txt'. The fuction returns the read file for main() to call, and print's
    the file's name so the user knows which file is read'''
        inFile1 = open(filename, "r")
        fileContentsList = inFile1.readlines()
        inFile1.close()
        totalChar =0    # Variable to store total number of characters
        for line in fileContentsList:    # reading all lines
            line = line.rstrip("\n")    # removing line end character '\n' from lines
            totalChar = totalChar + len(line) - line.count(" ")    # adding number of characters in line to total characters,
                                                                   # also removing number of whitespaces in current line
        print(filename.replace(".txt", "") + ":")  #this prints filename
        return totalChar
    
    main() # calling main function.
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-04-26
      • 1970-01-01
      • 2012-10-12
      • 1970-01-01
      • 1970-01-01
      • 2017-06-18
      • 2020-01-05
      相关资源
      最近更新 更多