字数Python 3.3程序中的可重试错误

use*_*537 0 python file-io file word-count python-3.x

我正在尝试完成一个简单的字数统计程序,它可以跟踪连接文件中的单词,字符和行数.

   # This program counts the number of lines, words, and characters in a file, entered by the user.
   # The file is test text from a standard lorem ipsum generator.
   import string
   def wc():
      # Sets the count of normal lines, words, and characters to 0 for proper iterative operation.
        lines = 0
        words = 0
        chars = 0
        print("This program will count the number of lines, words, and characters in a file.")
       # Stores a variable as a string for more graceful coding and no errors experienced previously. 
       filename =("test.txt")
       # Opens file and stores it as new variable, and loops through each line once the connection   with file is made.
       with open(filename, 'r') as fileObject:
             for l in fileObject:
                # Splits text file into each individual word for word count.
                words = l.split()

                lines += 1
                words += len(words)
                chars += len(l)
        print("Lines:", lines)
        print("Words:", words)
        print("Characters:", chars)

    wc()

    while 1:
        pass
Run Code Online (Sandbox Code Playgroud)

现在,如果一切顺利,它应该打印文件中的行,字母和单词的总数,但我得到的是这条消息:

"words + = len(words)TypeError:'int'对象不可迭代"

怎么了?

解决了!新代码:

    # This program counts the number of lines, words, and characters in a file, entered by the user.
    # The file is test text from a standard lorem ipsum generator.
    import string
    def wc():
        # Sets the count of normal lines, words, and characters to 0 for proper iterative operation.
        lines = 0
        words = 0
        chars = 0
        print("This program will count the number of lines, words, and characters in a file.")
        # Stores a variable as a string for more graceful coding and no errors experienced previously. 
        filename =("test.txt")
        # Opens file and stores it as new variable, and loops through each line once the connection with file is made.
        with open(filename, 'r') as fileObject:
            for l in fileObject:
                # Splits text file into each individual word for word count.
                wordsFind = l.split()

                lines += 1
                words += len(wordsFind)
                chars += len(l)
                 print("Lines:", lines)
                 print("Words:", words)
                 print("Characters:", chars)

    wc()

    while 1:
        pass
Run Code Online (Sandbox Code Playgroud)

And*_*ter 5

看起来你正在words为你的计数使用变量名,也为你的结果使用l.split().您需要通过为它们使用不同的变量名来区分它们.

  • +1.起初,这看起来像是用于不同语言的人的范围混淆.但实际上,他试图在同一行中使用它们,`words + = len(words)`.无论你如何解释它,你要么试图`len`一个int,要么将int附加到一个字符串列表中...... (2认同)