2017-12-07 4 views
0

저는 열린 텍스트 파일에서 두 개의 사전 (비슷한 작성자 및 수상한 상)을 업데이트하는 기능을 개발 중입니다. 텍스트 파일은 다음과 같습니다.텍스트 파일에서 사전을 만들 때 오류가 발생했습니다.

Brabudy, Ray 
Hugo Award 
Nebula Award 
Saturn Award 
Ellison, Harlan 
Heinlein, Robert 
Asimov, Isaac 
Clarke, Arthur  

Ellison, Harlan 
Nebula Award 
Hugo Award 
Locus Award 
Stephenson, Neil 
Vonnegut, Kurt 
Morgan, Richard 
Adams, Douglas 

등등. 첫 번째 이름은 저자 이름 (성, 이름, 성)이며, 그 다음에는 그들이 수여 한 상, 그리고 그와 비슷한 저자가 나옵니다. 이것은 내가 지금까지 가지고있는 것입니다 :

def load_author_dicts(text_file, similar_authors, awards_authors): 
    name_of_author = True 
    awards = False 
    similar = False 
    for line in text_file: 
     if name_of_author: 
      author = line.split(', ') 
      nameA = author[1].strip() + ' ' + author[0].strip() 
      name_of_author = False 
      awards = True 
      continue 
     if awards: 
      if ',' in line: 
       awards = False 
       similar = True 
      else: 
       if nameA in awards_authors: 
        listawards = awards_authors[nameA] 
        listawards.append(line.strip()) 
       else: 
        listawards = [] 
        listawards.append(line.strip() 
        awards_authors[nameA] = listawards 
     if similar: 
      if line == '\n': 
       similar = False 
       name_of_author = True 
      else: 
       sim_author = line.split(', ') 
       nameS = sim_author[1].strip() + ' ' + sim_author[0].strip() 
       if nameA in similar_authors: 
        similar_list = similar_authors[nameA] 
        similar_list.append(nameS) 
       else: 
        similar_list = [] 
        similar_list.append(nameS) 
        similar_authors[nameA] = similar_list 
       continue 

위대한 작품! 그러나 텍스트 파일에 이름이 포함 된 항목 (예 : 상장 및 유사 저자 없음)이 있으면이 부분에 이 표시됩니다.

어떻게 해결할 수 있습니까? 그 지역의 'try, except function' 일 가능성이 있습니까?
또한 계속 기능을 제거하는 데 신경 쓰지 않을 것입니다. 계속 유지할 방법을 모르겠습니다. 나는 아직도 이것에 아주 새롭다, 그래서 어떤 도움든지 매우 평가 될 것입니다! 나는 계속 노력하고 있고, 내가 변경하고 싶지 않았던 다른 섹션을 바꾼다. 그래서 나는 전문가에게 물어볼 것이라고 생각했다.

+1

쉼표가없는 파일에 빈 줄이 /가 있습니다. 그래서'sim_author'는 비어 있거나 내부에 오직 하나의 항목 만 가질 수 있습니다. 그 루프 안의 보너스 깃발을 재설정하지 않습니다. –

답변

1

이렇게하면 어떨까요? 데이터를 가져온 다음 원하는 방식으로 사전을 조작하십시오.

있는 test.txt는 데이터

Brabudy, Ray 
Hugo Award 
Nebula Award 
Saturn Award 
Ellison, Harlan 
Heinlein, Robert 
Asimov, Isaac 
Clarke, Arthur 

Ellison, Harlan 
Nebula Award 
Hugo Award 
Locus Award 
Stephenson, Neil 
Vonnegut, Kurt 
Morgan, Richard 
Adams, Douglas 

그리고 그것을 구문 분석하려면 코드가 포함되어 있습니다.

award_parse.py

data = {} 
name = "" 
awards = [] 

f = open("test.txt") 

for l in f: 
    # make sure the line is not blank don't process blank lines 
    if not l.strip() == "": 

     # if this is a name and we're not already working on an author then set the author 
     # otherwise treat this as a new author and set the existing author to a key in the dictionary 
     if "," in l and len(name) == 0: 
      name = l.strip() 

     elif "," in l and len(name) > 0: 
      # check to see if recipient is already in list, add to end of existing list if he/she already 
      # exists. 
      if not name.strip() in data: 
       data[name] = awards 
      else: 
       data[name].extend(awards) 

      name = l.strip() 
      awards = [] 

     # process any lines that are not blank, and do not have a , 
     else: 
      awards.append(l.strip()) 


f.close() 


for k, v in data.items(): 
    print("%s got the following awards: %s" % (k,v)) 
관련 문제