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 に答える