2016-10-20 7 views
0

나는 셸에서 파일을 열고 읽으며 내용이 무엇인지 해석하려고하는 Concordance 프로그램을 작성하려고합니다. 그런 다음 텍스트와 관련하여 단어의 위치와 함께 알파벳 순서로 단어를 인쇄하고 싶습니다. 지금까지 나는 이것을 가지고있다 :파이썬에서의 일치. 알파벳 순서

import sys 

if len(sys.argv) < 2: 
    filename= input('what file? ') 
    handle = open(filename, 'r') 
elif sys.argv[1] == '-': 
    handle = sys.stdin 
else: 
    handle = open(sys.argv[1], 'r') 

appearances = [] 
position = 0 
allwords = {} 
for line in handle.readlines(): 
    words = line.split() 
    for w in words: 
     w = w.lower() 
     if w in allwords.keys(): 
      allwords [w] += 1 
     else: 
      allwords[w] =1 
     for w in allwords: 
      if not w in allwords: 
       allwords[w] = [] 
       appearances.append(position) 
       position +=1 
      else: 
       appearances.append(position) 
       position += 1 
handle.close() 

keys = sorted(allwords.keys()) 
for k in keys: 
    print('{:15s} {} {}'.format(k, appearances, position)) 

지금까지 코드는 나에게 정확하게 알파벳 순서로 단어를 준다. 그러나, 그것은 나에게 말의 위치가 적절한 위치를 제공하지 못한다. 나는 파이썬에 다소 익숙하다. 그래서 조금이라도 기본을 유지하려고한다면 그것을 높이 평가할 것이다. 또한 구두점을 사용하여 좀 더 "독창적"으로 만들고 싶습니다.

+2

단어에 해당하는 줄 번호를 가져 오시겠습니까? – Chr

+0

파일에서 단어를 원하면 각 단어가 나타나는 횟수와 각 단어의 위치가 필요합니까? –

+0

StackOverflow에 오신 것을 환영합니다. 귀하의 질문에서 정확히 무엇을 달성하려고하는지 명확하지 않습니다. 요구 사항을 명확히하고 예상되는 입력 및 출력 예제를 제공하십시오. 가능한 한 구체적이어야 더 나은 답변으로 이어질 것입니다. –

답변

0

필자가 이해할 수있는 한, 파일에있는 단어의 실제 위치가 걱정되는 동시에 알파벳 순서로 단어를 인쇄하기를 원합니다. 다음 코드를 사용할 수 있습니다 :

우리는 항상 각 단어의 수와 특정 단어의 위치를 ​​저장하는 목록의 길이를 갖습니다.

# allwords is a dictionary which uses word as the key and the list of position of the word in the file as the value. 
# The position will be recored as (line_number, word_number) tuple where word_number is position of the word in that particular line. 

allwords = {} 

# Get the index of the line as well. 
for lineno,line in enumerate(handle.readlines()): 

    words = line.split() 

    # Get the word index as well. 
    for wordno,w in enumerate(words): 

     w = w.lower() 

     # Make the position tuple and append in the list of appearances for that particular word. 
     position = (lineno+1, wordno+1) 

     if w not in allwords.keys(): 

      allwords[w] = [] 

     allwords[w].append(position) 



for key in sorted(allwords.keys()): 
    print(key + " appeared " + str(len(allwords[key])) + " number of times and positions are:") 
    for tup in allwords[key]: 
     print(tup)