2012-10-29 3 views
0

연결된 파일의 단어, 문자 및 줄 수를 추적하는 간단한 단어 수 계산 프로그램을 완료하려고합니다. 모두가 잘된다면 이제단어 수 Python 3.3 프로그램에서 반복 가능한 오류

# 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 (단어) TypeError : 'int'객체가 반복 가능하지 않음 "

무엇이 잘못 되었습니까?

해결! 새로운 코드는 : 당신이 l.split()의 결과를 또한 카운트 변수 이름 words을 사용하고있는 것처럼

# 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 

답변

5

것 같습니다. 서로 다른 변수 이름을 사용하여 구분해야합니다.

+2

+1. 처음에는 다른 언어로 익숙한 사람이 범위를 혼동하는 것처럼 보입니다. 그러나 실제로, 그는 같은 줄에 'words + = len (words)'를 사용하려고합니다. 아무리 해석하려고해도 int를'len'하거나 문자열 목록에 int를 추가하려고합니다 ... – abarnert

+0

이제 작동합니다. 증거를 위해 최종 작업 코드를 추가했습니다. @Andew 감사합니다! 필자는 주로 Java에 익숙해 져있어 비교적 새로운 Python 3.3 사용자로서 저의 실수에 사과합니다. – user1739537