2013-12-13 1 views
-1

이 프로그램은 여기에 연결되어있는 두 개의 .CSV 파일 중 데이터를 가져옵니다 : 두 파일의 각 쉼표 후 아무것도 의산 데 https://drive.google.com/folderview?id=0B1SjPejhqNU-bVkzYlVHM2oxdGs&usp=sharing(파이썬) .CSV에서 데이터를 가져올 때 인덱스가 범위를 벗어났습니다?

을,하지만 내 범위 로직은 어떻게 든 잘못된 것입니다. I는 101 라인에 추적 오차를하고 있는데 :

"라인 101 calc_corr에서 : sum_smokers_value = sum_smokers_value + 플로트 (s_percent_smokers_data [R] [1]) IndexError : 범위 밖의리스트 인덱스"

I 다른 시간 [k] [1]이 나타나기까지 똑같이한다고 가정하십시오.

많은 문제를 미리 해결해 주셔서 감사합니다.

프로그램은 지금까지입니다 : 데이터 파일의 각 행에서

# this program opens two files containing data and runs a corralation calculation 

import math 

def main(): 


    try: 
     print('does smoking directly lead to lung cancer?') 
     print('''let's find out, shall we?''''') 
     print('to do so, this program will find correlation between the instances of smokers, and the number of people with lung cancer.') 

     percent_smokers, percent_cancer = retrieve_csv() 

     s_percent_smokers_data, c_percent_cancer_data = read_csv(percent_smokers, percent_cancer) 

     correlation = calc_corr(s_percent_smokers_data, c_percent_cancer_data,) 

     print('r_value =', corretation) 

    except IOError as e: 
     print(str(e)) 
     print('this program has been cancelled. run it again.') 



def retrieve_csv(): 
    num_times_failed = 0 
    percent_smokers_opened = False 
    percent_cancer_opened = False 



    while((not percent_smokers_opened) or (not percent_cancer_opened)) and (num_times_failed < 5): 

     try: 

      if not percent_smokers_opened: 
       percent_smokers_input = input('what is the name of the file containing the percentage of smokers per state?') 
       percent_smokers = open(percent_smokers_input, 'r') 
       percent_smokers_opened = True 

      if not percent_cancer_opened: 
       percent_cancer_input = input('what is the name of the file containing the number of cases of lung cancer contracted?') 
       percent_cancer = open(percent_cancer_input, 'r') 
       percent_cancer_opened = True 

     except IOError: 
      print('a file was not located. try again.') 
      num_times_failed = num_times_failed + 1 

    if not percent_smokers_opened or not percent_cancer_opened: 
     raise IOError('you have failed too many times.') 

    else: 
     return(percent_smokers, percent_cancer) 



def read_csv(percent_smokers, percent_cancer): 
    s_percent_smokers_data = [] 
    c_percent_cancer_data = [] 

    empty_list = '' 


    percent_smokers.readline() 
    percent_cancer.readline() 
    eof = False 

    while not eof: 
     smoker_list = percent_smokers.readline() 
     cancer_list = percent_cancer.readline() 

     if smoker_list == empty_list and cancer_list == empty_list: 
      eof = True 

     elif smoker_list == empty_list: 
      raise IOError('smokers file error') 

     elif cancer_list == empty_list: 
      raise IOError('cancer file error') 


     else: 
      s_percent_smokers_data.append(smoker_list.strip().split(',')) 
      c_percent_cancer_data.append(cancer_list.strip().split(',')) 


    return (s_percent_smokers_data, c_percent_cancer_data) 


def calc_corr(s_percent_smokers_data, c_percent_cancer_data): 

    sum_smokers_value = sum_cancer_cases_values = 0 
    sum_smokers_sq = sum_cancer_cases_sq = 0 
    sum_value_porducts = 0 
    numbers = len(s_percent_smokers_data) 

    for k in range(0, numbers): 
     sum_smokers_value = sum_smokers_value + float(s_percent_smokers_data[k][1]) 
     sum_cancer_cases_values = sum_cancer_cases_values + float(c_percent_cancer_data[k][1]) 

     sum_smokers_sq = sum_smokers_sq + float(s_percent_smokers_data[k][1]) ** 2 
     sum_cancer_cases_sq = sum_cancer_cases_sq + float(c_percent_cancer_data[k][1]) ** 2 

     sum_value_products = sum_value_products + float(percent_smokers[k][1]) ** float(percent_cancer[k][1]) 

    numerator_value = (numbers * sum_value_products) - (sum_smokers_value * sum_cancer_cases_values) 
    denominator_value = math.sqrt(abs((numbers * sum_smokers_sq) - (sum_smokers_value ** 2)) * ((numbers * sum_cancer_cases_sq) - (sum_cancer_cases_values ** 2))) 



    return numerator_value/denominator_value 


main() 
+0

제 생각 엔 CSV 파일 중 하나의 라인에 쉼표가 없습니다. 'csv' 모듈을 사용하는 대신 CSV 파일을 직접 파싱해야하는 이유가 있습니까? 'csv.reader'와'zip'을 사용하면 프로그램의 복잡성을 줄일 수 있습니다 (실제로 파일의 행 수가 다른 경우를 감지해야하는 경우 itertools.zip_longest). – Blckknght

+0

@Blckknght, 우분투를 실행합니다. 그래서 LibreOffice calc에서 파일을 만들었습니다. MS의 복사본은 Excel로 저장되어 CSV 파일로 저장되었습니다. 단어 문서 작성과 같은 더 좋은 방법이 있습니까? 감사! – elm95

답변

0

값은 분리 된 것이 아니라 탭은 쉼표로 구분되지 않습니다. '\t'에 대해 분할 할 ',' 구분 문자를 변경해야합니다. 또는 csv 모듈을 사용하고 구분 기호가 '\t'임을 알리십시오. csv 모듈에 대한 자세한 내용은 the documentation에서 확인할 수 있습니다.

+0

전 세계적으로 CSV 파일을 가져와야한다고 가정합니다. – elm95

+0

나는 이해하고 있는지 잘 모르겠다. 코드의 직접적인 문제는 두 개의'split' 호출에서''\ t "'에 대해'',''를 바꿔서 해결할 수 있습니다. (아직 코드를 테스트하지 않았으므로 다른 문제가있을 수 있습니다.)'csv' 모듈을 사용하기 위해 전환하는 것이 더 큰 변화입니다. 모듈 가져 오기는 첫 단계이지만 아무것도 수행하지 않습니다. – Blckknght

+0

제대로 작동합니다. 또한 19 번과 117 번 줄에서 오타를 발견하고 수정했습니다. 감사합니다! – elm95

관련 문제