簡體   English   中英

字數統計Python 3.3程序中的可迭代錯誤

[英]Iterable error in word count Python 3.3 program

我正在嘗試完成一個簡單的單詞計數程序,該程序可以跟蹤連接文件中的單詞,字符和行數。

   # 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

現在,如果一切順利,則應該打印文件中的行,字母和單詞的總數,但是我得到的只是以下消息:

“單詞+ = 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

看來您正在使用變量名words進行計數,還使用了l.split()的結果。 您需要通過使用不同的變量名稱來區分它們。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM