2016-11-27 2 views
-1

지난 며칠 동안이 도움말을 찾으려고했지만 아무것도 찾지 못했습니다.파이썬에서 CSV 파일의 특정 행을 읽는 방법

저는 현재 레벨 컴퓨터 과학을 공부하고 있습니다. 이 프로젝트는 통화 변환기이며 사용자가 통화 코드를 입력 한 다음 프로그램에서이 정보를 가져 와서 CSV 파일과 비교하는 방법을 알고 싶습니다. 통화 코드가 파일에있는 경우 프로그램에서 입력의 통화 코드와 일치하는 전환율을 가져와 합계/등식에 사용하여 변환을 완료해야합니다. 시도하고 CSV 파일을 구현하는 몇 가지 방법을 시도했지만 작동하도록 얻을 수 없습니다. 내가 파이썬 3.5.2

난 그냥 그런 CSV 파일을 구현하는 방법의 예에 대한 전체 코드를 요구 아니에요을 사용하고

. 내가 이렇게 일찍 I는를 사용 들었다 작업을 완료하기 때문에 전환을 달성하는 경우에 사용

Currency,  Code, Rate 
Canadian Dollar, CAD, 1.3457 
Swiss Franc,  CHF, 1.0129 
British Pounds, GBP, 0.8056 
Japanese Yen, JPY, 111.52 
Bitcoin,   BTC, 0.001351 

내 첫 번째 프로그램, ELIF 및 else 문 :

내 CSV 파일 중 하나의 예입니다 CSV 파일 대신.

def Amount_Input(): 
    while True: 
     try: 
      global amount 
      amount = float(input("Enter amount to be converted:")) 
      Currency_From() 
      break 
     except ValueError: 
      print("Invalid Entry, Please enter a valid entry as a decimal number.") 
      continue 


def Currency_From(): 
    currencyInput1 = input("Enter the currency you wish to convert from:") 
    if currencyInput1 in ['USD', 'usd']: 
     USD() 
    elif currencyInput1 in ['GBP', 'gbp']: 
     GBP() 
    elif currencyInput1 in ['EUR', 'eur']: 
     EUR() 
    elif currencyInput1 in ['BTC', 'btc']: 
     BTC() 
    else: 
     print("Invalid entry") 
     Currency_From() 


def USD(): 
    currencyInput2 = input("Enter the currency you want to convert to:") 
    if currencyInput2 in ['GBP', 'gbp']: 
     print("You are converting", amount, "USD to GBP.") 
     converted_amount = amount*0.81 
     print(converted_amount) 
    elif currencyInput2 in ['EUR', 'eur']: 
     print("You are converting", amount, "USD to EUR.") 
     converted_amount = amount*0.94 
     print(converted_amount) 
    elif currencyInput2 in ['BTC', 'btc']: 
     print("You are converting", amount, "USD to BTC.") 
     converted_amount = amount*0.0013 
     print(converted_amount) 
    else: 
     print("Invalid Entry") 
     USD() 


def GBP(): 
    currencyInput2 = input("Enter the currency you want to convert to:") 
    if currencyInput2 in ['USD', 'usd']: 
     print("You are converting", amount, "GBP to USD.") 
     converted_amount = amount*1.24 
     print(converted_amount) 
    elif currencyInput2 in ['EUR', 'eur']: 
     print("You are converting", amount, "GBP to EUR.") 
     converted_amount = amount*1.17 
     print(converted_amount) 
    elif currencyInput2 in ['BTC', 'btc']: 
     print("You are converting", amount, "GBP to BTC.") 
     converted_amount = amount*0.0017 
     print(converted_amount) 
    else: 
     print("Invalid Entry") 
     GBP() 


def EUR(): 
    currencyInput2 = input("Enter the currency you want to convert to:") 
    if currencyInput2 in ['USD', 'usd']: 
     print("You are converting", amount, "EUR to USD.") 
     converted_amount = amount*1.06 
     print(converted_amount) 
    elif currencyInput2 in ['GBP', 'gbp']: 
     print("You are converting", amount, "EUR to GBP.") 
     converted_amount = amount*0.85 
     print(converted_amount) 
    elif currencyInput2 in ['BTC', 'btc']: 
     print("You are converting", amount, "EUR to USD.") 
     converted_amount = amount*0.0014 
     print(converted_amount) 
    else: 
     print("Invalid Entry") 
     EUR() 


def BTC(): 
    currencyInput2 = input("Enter the currency you want to convert to:") 
    if currencyInput2 in ['USD', 'usd']: 
     print("You are converting", amount, "BTC to USD.") 
     converted_amount = amount*746.20 
     print(converted_amount) 
    elif currencyInput2 in ['GBP', 'gbp']: 
     print("You are converting", amount, "BTC to GBP.") 
     converted_amount = amount*600.89 
     print(converted_amount) 
    elif currencyInput2 in ['EUR', 'eur']: 
     print("You are converting", amount, "BTC to EUR.") 
     converted_amount = amount*704.36 
     print(converted_amount) 
    else: 
     print("Invalid Entry") 
     BTC() 


print(Amount_Input()) 
+1

내가이 작업을 수행 중이라면 처음부터 전체 파일을 읽고 사전에 매핑 할 사전 통화 코드를 작성했습니다. –

+0

어쩌면 당신은 이것을 줄여서 그들의 구현을 점검 할 수 있습니다 : https://pypi.python.org/pypi/CurrencyConverter/0.5 – MYGz

답변

0

여기 당신은 그들이 그것을 선으로 줄을 읽어주는 첫 번째 예에서 볼 수있는 documentation on using csv.reader

입니다 :

초기 코드이었다.

import csv 
with open('currency.csv', 'rb') as csvfile: 
    currencyreader = csv.reader(csvfile) 
    for row in currencyreader: 
     print row 

을 그리고 출력 될 것입니다 :

['Currency', 'Code', 'Rate'] 
['Canadian Dollar CAD 1.3457', 'CAD', '1.3457'] 
['Swiss Franc CHF 1.0129', 'CHF', '1.0129'] 
['British Pounds GBP 0.8056', 'GBP', '0.8056'] 
['Japanese Yen JPY 111.52', 'JPY', '111.52'] 
['Bitcoin BTC 0.001351', 'BTC', '0.001351'] 

당신은 설정은 다음과 비슷한 모습이 될 것입니다 귀하의 파일에 대해 을 (그것이 정상 CSV 인 경우에 당신은 구분 기호 또는 quotechar을 지정할 필요가 없습니다) csvfile 객체에 대해 열린 파일 그런 다음 파일의 내용을 통화 판독기 개체로 읽습니다. 그런 다음 행별로 반복합니다.

사용자 입력 읽기에서 행을 매개 변수로 사용하는 것으로 기능을 변경해야합니다.

또한 개인적인 취향 일 수도 있습니다.하지만 사실을 제거하는 코드는 리팩터링하여 나를 굴복하게 만듭니다.

0

저는 학교 프로젝트를 위해 파이썬 스킬을 연습해야하지만이 기능은 이미 기존 라이브러리에 의해 캡처 된 것으로 알고 있습니다. Numpy는 아마 번호가있는 라이브러리를 # 1로 갈 것입니다. 이것은 내가 프로젝트를 해결 할 방법은 다음과 같습니다

from io import StringIO 
import numpy as np 

다음 줄이

d = np.recfromcsv('currencies.csv', delimiter=',') 

는 이제 개별 통화에 액세스하는 'D'를 사용할 수있는 모든 파일 읽기 및 디코딩을 수행합니다.

print(d[1]) # shows: (b'Swiss Franc', b'  CHF', 1.0129) 
print(d[1][2])# shows: 1.0129 
관련 문제