2014-06-17 3 views
5

초보 프로그래머. 자가 학습 Python. Stackoverflow에 대한 첫 번째 질문.파이썬에서 둘 이상의 데이터 구조 (dicts) 만들기

나는 가격, 등급 및 요리 유형의 사용자 선택에 따라 식당을 추천하는 프로그램을 작성하려고합니다. 이를 위해, 프로그램은 세 개의 데이터 구조를 구축 :

#Rest name 
#Rest Rating 
#Rest Price range 
#Rest Cuisine type 
# 
#Rest2 name 

:

# Initiating the data structures 

name_rating = {} 
price_name = {} 
cuisine_name = {} 

데이터는 다음과 같은 서식 restaurants.txt에서 온다 [나는 중간 단계에서 여전히입니다]

다음 함수는 원하는 줄의 문자열 만 반환합니다.

# The get_line function returns the 'line' at pos (starting at 0) 
def get_line(pos): 
    fname = 'restaurants.txt' 
    fhand = open(fname) 
    for x, line in enumerate(fhand): 
     line = line.rstrip() 
     if not pos == x: continue 
     return line 


# Locating the pos's of name, rate, price & cuisine type for each restaurant 
# Assumes uniform txt file formatting and unchanged data set 

name_pos = [x for x in range(0,84,5)] 
rate_pos = [x for x in range(1,84,5)] 
price_pos = [x for x in range(2,84,5)] 
cuis_pos = [x for x in range(3,84,5)] 

Increme 각 식당에 대한 데이터를 별도로 얻으려면 NTS를 5로 제한하십시오.

fname = 'restaurants.txt' 
fhand = open(fname) 

다음 반환 이름의 사전 : 등급

# Builds the name_rating data structure (dict) 
def namerate(): 
    for x, line in enumerate(fhand): 
     line = line.rstrip() 
     for n, r in zip(name_pos, rate_pos): 
      if not n == x: continue 
      name_rating[line] = name_rating.get(line, get_line(r)) 
    return name_rating 

다음 반환

가격의 사전 : 기능을

print pricename() 
print namerate() 

QUESTIO를 호출

# Builds the price_name data structure (dict) 
def pricename(): 
    for x, line in enumerate(fhand): 
     line = line.rstrip() 
     for p, n in zip(price_pos, name_pos): 
      if not p == x: continue 
      price_name[line] = price_name.get(line, get_line(n)) 
    return price_name 

이름 N : 함수를 호출 할 때 왜 내가 먼저 호출 한 함수 만 성공합니까? 두 번째 딕트는 비어 있습니다. 별도로 호출하면 데이터 구조가 작성됩니다. 둘 다 호출하면 첫 번째 만 성공합니다.

p.s. 나는이 모든 것을 훨씬 더 빨리 할 수 ​​있다고 확신하지만, 지금은 스스로 그렇게하려고 노력 중입니다. 그래서 어떤 것은 중복되거나 불필요하게 보일 수도 있습니다. 나와 함께하시기 바랍니다 곰 :

+2

문서를 열고 첫 번째 함수에서 읽기, 당신이 그것의 끝에 도달 , 그리고 두 번째로, 당신은 끝 *보다 더 읽으려고하고 있습니다. 그러므로 불가능합니다. –

답변

1

당신은 다시 seek 방법을 사용하여 시작에 파일 위치를 설정할 수 있습니다 (docs 참조)

f = open("test.txt") 

for i in f: 
    print(i) 
# Print: 
    # This is a test first line 
    # This is a test second line 

for i in f: 
    print(i) 
# Prints nothig 

f.seek(0) # set position to the beginning 

for i in f: 
    print(i) 
# Print: 
    # This is a test first line 
    # This is a test second line 
+0

Gotcha. wasnt는 내가 재설정 할 필요가있다라는 것을 알고있다. 건배 – Abd00s

+0

내가 명시 적으로 언급하지 않은 두드러진 점은 파일 객체가 상태 저장되어 있고 커서가 앞으로 움직여 커서가 앞으로 갈 때까지 더 이상 읽을 수 없다는 것입니다 ("position"). 데이터는 파일 객체의 반복을 위해 실행되지 않습니다. 한 가지 방법은 제안 된 방법이지만이 문제를 해결하는 다른 방법이 있습니다. 하나는 단순히 각 함수 내에서 파일을 다시 여는 것입니다. 다른 하나는 메모리 버퍼에 파일을 읽은 다음 그 파일을 조작하고 다른 하나는 멀티플렉싱 처리기를 갖는 것입니다. 파일을 다시 열거 나 탐색하는 것은 괜찮지 만 규모가 없습니다. –

관련 문제