0

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

   # 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

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

“words += len(words) TypeError: 'int' object is not iterable”

怎么了?

解决了!新代码:

    # 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
4

1 回答 1

5

看起来您正在使用变量名称words来计算计数,以及l.split(). 您需要通过为它们使用不同的变量名称来区分它们。

于 2012-10-29T21:52:15.393 回答