2016-07-01 1 views
0

두 개의 텍스트 파일을 참조하는 프로그램을 작성하고 있습니다. 하나는 문장의 통화 목록을 저장하고 하나는 현재 값을 저장합니다. 문장의 통화 값을 한 번만 저장하고 각 주문을 저장하여 화면에서 바꿀 수 있도록하고 싶습니다. 예 : 스털링, 유로 (하나의 파일로). 1,1,2 (주문 파일에서). 당신이 주로 먼저 통화를 색인하고 있기 때문에 당신은 오류가 발생하는 범위IndexError : 목록 색인이 범위를 벗어남 - 파이썬에서 출력을 저장하기 위해 txt 파일을 가져올 수 없습니다.

all_currency = [] 
value_of_currency = [] 

my_words_file = open("words.txt","r") 
my_words_document = my_words_file.readline() 
while my_words_document != "": 
     all_currency.append(my_words_document.strip()) 
     my_words_document = my_words_file.readline() 
print("output of the words in the saved list:",str(all_currency)) 
my_words_file.close() 
positions = "" 
my_numbers_file = open("numbers.txt","r") 
value_of_currency = my_numbers_file.readline().strip().split() 
my_numbers_file.close() 
for mynumbers in value_of_currency: 
    positions += all_currency[int(mynumbers)]+" " 

print("output of the positions in the saved list:",positions) 
+0

IndexError는 어느 라인에서 켜져 있습니까? 나는 그것의'position + = all_currency [int (mynumbers)] + ""''그 줄 앞에'int (mynumbers)'를 출력하고 그것이 무엇을 말하는지 보려고합니다. – Jeff

+0

오류의 흔적을 보여 주실 수 있습니까? –

+0

네, 그 줄입니다. –

답변

0

에서리스트 인덱스 : 나는 오류 메시지 IndexError가 계속. 이후로는 2 개의 통화 만 있기 때문에 세 번째 지수를 얻으려고하는 것입니다. arr [2]이 오류를 제공합니다.

+0

먼저 통화에 대한 색인을 생성하지 않으려면 어떻게합니까? 나는 텍스트 파일에 복제 된 단어를 원하지 않습니다. 나는 당신이 할 수있는 말을 한 번 할 수 있다고 생각하고 다음 각 번호 위치를 사용하여 그들을 함께 연결? –

+0

이전에 위치 문자열을 인쇄 할 때 그 시점에서 출력 목록이 비어 있기 때문에 아무것도 표시되지 않습니다. –

+0

다음과 같은 오류 메시지가 표시됩니다. 가장 최근에 호출 한 번호 : 파일 "/ Users/Matt/Desktop/stack"파일, 위치 + = all_currency [int (mynumbers)] + "" IndexError : list index 범위 초과 범위 >>> –

0
def read_words(words_file): 
return [word for line in open(words_file, 'r') for word in line.strip().split(',')] 

all_currency = read_words("a.txt") 
print(all_currency) 
value_of_currency = read_words("b.txt") 
print(value_of_currency) 

positions = "" 
for mynumbers in value_of_currency: 
     positions += all_currency[int(mynumbers)]+" " 
print("output of the positions in the saved list:",positions) 

#a.txt file contains currency: "Sterling,Euro,Dollar" 
#b.txt file contains currency: "1,1,2" 

실제로 원하는 출력을 얻지 못했지만 오류 문제가 해결되었습니다. 이전에 말한 것처럼 값이 인덱스 번호를 넘지 않도록해야합니다. 당신이 이해하기를 바랍니다.

+0

표시 방법 : –

관련 문제