2014-04-16 2 views
1

Windows의 명령 줄에서 텍스트 파일에 대해 프로그램 (word_count.py)을 실행하려고합니다. 그러나 파일을 읽는 동안 예외가 발생하고 예외가 발생합니다. 누군가 왜 저에게 말할 수 있습니까?Python : 읽기 위해 파일을 열 수 없습니다.

import sys 
import re 
import string 

def Usage(): 
print "Usage:word_count.py [doc1] [doc2] ... [docN]" 

if len(sys.argv) == 1: 
Usage() 
sys.exit() 

for fn in sys.argv[1:]: 
    try: 
     with open(fn) as textf: 
     word_map = {} 
     total_cnt = 0 

     # reads one line at a time 
     for line in textf: 
      line = line.strip() 
      if not line: 
       continue 

      tempwords = line.split() 

      for w in tempwords: 
       w = re.sub('[%s]' % re.escape(string.punctuation), '', w) 
       if w: 
        if w.lower() in word_map: 
         word_map[w.lower()] += 1 
        else: 
         word_map[w.lower()] = 1 
        total_cnt += 1 
     print fn+' ------ total word count: '+str(total_cnt) 

    output_f_name = 'word_count_'+fn 
    with open(output_f_name, 'wb') as output: 
     for ele in sorted(word_map.items(), key=lambda x:x[1], reverse=True): 
      output.write('{} {}\n'.format(str(ele[1]).rjust(6), ele[0].ljust(2))) 
    except IOError: 
     print 'Cannot open file %s for reading' % fn 
     exit(1) 

.py 파일 파일과 .txt 파일 모두 내 바탕 화면에있는 내가 사용하여 명령 행에서 프로그램을 실행하고 있습니다 :

C를 : 여기에

는 평 파일입니다 \ Users \ Me \ Desktop> word_count.py [file.txt]

+1

자세한 정보를 제공 할 수 있습니까? 오류 로그? – njzk2

+1

(들여 쓰기가 잘못되었습니다. 수정하십시오) – njzk2

+1

명령이'python word_count.py file.txt'가 아니십니까? (나는'python'이'% PATH %'에 있다고 가정하고 있습니다.) – SlightlyCuban

답변

2

문자 그대로 대괄호로 파일 이름을 명령 줄에 둘러 쌓으려면 문제가 될 수 있습니다. 인수는 목록으로 처리되지만 유추되므로 두 항목 사이에 공백을 넣어 목록 항목을 구분할 수 있습니다.

+0

지금 작동하게되었습니다. 고마워요. – Brian

0

대괄호를 대문자로 사용하지 마십시오.

사용이 대신 : 대괄호는 일반적으로 인수를 나타내는 데 사용됩니다

word_count.py file.txt 

는 사용 문자열에서, 선택 사항입니다.

+0

괄호와 함께 또는없이 실행하는 것은 결과에 영향을 미치지 않습니다. 나는 여전히 예외를 throw합니다 "읽기 위해 file.txt를 열 수 없습니다." – Brian

+0

@ user1781516 예외 메시지를 인쇄 할 수 있습니까? ('IOError, e : print "...", e' 제외) – anana

+0

감사합니다. – Brian

관련 문제