2016-04-14 27 views
0

数値に関連付けられた名前のフィールドを持つテキストファイルがあります。フィールドは空白行で区切られています。コードは、選択された名前とそれに関連するフィールドを提供する必要があります。テキストファイルを解析中にエラーが発生しました -

1,Hospital_Records 
2,Exit 
Enter your choice: 1 
Enter your first and last name: John Wilson 
Name: John Wilson 
Days in Hospital: 3 
Daily Rate: 400.0 
Service Charges: 1000.0 
medication_Charges: 5987.22 
Total Charges: 8187.22 

Traceback (most recent call last): 
    File "E:/test_file_parse.py", line 63, in <module> 
    main() 
    File "E:/test_file_parse.py", line 29, in main 
    days_in_hospital = int(file.readline()) 
ValueError: invalid literal for int() with base 10: '\n' 

が、私は私のコードおよびテキストファイルを提供しています:ここに私のスタックトレースです

def main(): 
#create a bool variable to use as a flag 
found = False 

searchName='' 
days_in_hospital=0 
daily_rate=0.0 
service_charge= 0.0 
medication_charges= 0.0 
choice=0 
total_charges= 0.0 

while choice!=2: 
    print("1,Hospital_Records") 
    print("2,Exit") 

    choice= int(input("Enter your choice: ")) 

    if choice==1: 
     #Get the search value 
     searchName= input("Enter your first and last name: ") 
     file= open("c:\\Python34\HospitalRecords.txt", "r") 
     #Read the first record's name field 
     record = file.readline() 

     #Read the rest of the file 
     while record!='': 
      days_in_hospital = int(file.readline()) 
      daily_rate = float(file.readline()) 
      service_charge = float(file.readline()) 
      medication_charges = float(file.readline()) 
      total_charges = ((days_in_hospital * daily_rate) + 
      service_charge + medication_charges) 


      #strip the newline character from the record 
      record= record.rstrip('\n') 

      #determine if this record matches the search value 
      if record==searchName: 
       print("Name: " ,searchName) 
       print("Days in Hospital: " , days_in_hospital) 
       print("Daily Rate: " , daily_rate) 
       print("Service Charges: " , service_charge) 
       print("medication_Charges: " , medication_charges) 
       print("Total Charges: " ,total_charges) 
       print() 
       #set the found flag to True 
       found = True 

    elif choice==2: 
     print("You are successfully exited your program") 
    else: 
     print("Invalid entry") 

     #If the search value was not found in the file 
     #display a message 
    if not found: 
      print("That name was not found in the file.") 

file.close()   

メイン()ここで

はテキストファイルです:

John Wilson 
3 
400.00 
1000.00 
5987.22 

Charles Sanders 
10 
12000.34 
2487.77 
8040.66 

Susan Sarandon 
1 
300.22 
8463.88 
12777.33 

Mary Muffet 
8 
4976.55 
4050.00 
15839.20 

また、John Wilsonの最初の名前以外の名前を入力すると、次のエラーが表示されます。

1,Hospital_Records 
2,Exit 
Enter your choice: 1 
Enter your first and last name: Susan Sarandon 
Traceback (most recent call last): 
    File "E:/test_file_parse.py", line 63, in <module> 
    main() 
    File "E:/test_file_parse.py", line 29, in main 
    days_in_hospital = int(file.readline()) 
ValueError: invalid literal for int() with base 10: '\n' 
+0

を多分 '' int型(。file.readline()ストリップ( '\ n')で)してみてください? – Eli

+0

テキストファイルのレコード間に余分な行があるようです。余分な 'file.readline()'を投げて空の行を無視し、それがどのように動作するかを見てください。また、警告の言葉:テキストファイルのファイルパスにエスケープされていないバックスラッシュがあります。 – Kupiakos

+0

Eli、Kupiakos、これらの修正は何も変更しませんでした。まだ同じエラーが発生しています。私は余分な 'file.readline'を投げたときに気付いた。ファイル名の次のレコードである 'Charles Sanders'は、基数10のint()の無効なリテラルの最後に現れた。 'Charles Sanders' – brohjoe

答えて

0

コードにロジックエラーがあり、ユーザーとのやりとりがスムーズに行えませんでした。 (例えば、レコード名の扱い、レコード間の空白行、ファイルが閉じられた時など)私はあなたのロジックを修正しました。これはあなたが探している結果を与えるかどうかを確認します:

FILE_NAME = r"c:\\Python34\HospitalRecords.txt" 

def main(): 

    choice = 0 

    while choice != 2: 
     print("1) Hospital_Records") 
     print("2) Exit") 

     choice = int(input("Enter your choice: ")) 

     if choice == 1: 
      # create a bool variable to use as a flag 
      found = False 
      # Get the search value 
      searchName = input("Enter your first and last name: ") 
      file = open(FILE_NAME) 
      # Read the first record's name field 
      record_name = file.readline().rstrip('\n') 

      # Read the rest of the file 
      while record_name != '': 
       days_in_hospital = int(file.readline()) 
       daily_rate = float(file.readline()) 
       service_charge = float(file.readline()) 
       medication_charges = float(file.readline()) 

       # determine if this record matches the search value 
       if record_name == searchName: 
        print("Name: ", searchName) 
        print("Days in Hospital: ", days_in_hospital) 
        print("Daily Rate: ", daily_rate) 
        print("Service Charges: ", service_charge) 
        print("medication_Charges: ", medication_charges) 

        total_charges = ((days_in_hospital * daily_rate) + service_charge + medication_charges) 

        print("Total Charges: ", total_charges) 
        print() 

        # set the found flag to True 
        found = True 

        break 

       record_separator = file.readline() 

       # strip the newline character from the record 
       record_name = file.readline().rstrip('\n') 

      file.close() 

      if not found: 
       # If the search value was not found in the file 
       # display a message 
       print("That name was not found in the file.") 
     elif choice == 2: 
      print("You successfully exited the program.") 
     else: 
      print("Invalid entry!") 

main() 
0

ファイルを1行ずつ読み込みましたが、コードで想定されている形式が実際のファイルと一致しません。

あなたの最初のreadline()はファイルの最初の行( "John Wilson")をつかんで、次に4行以上readline()を実行して、次の行のすべての数字を取得します。

この時点で、次のreadline()はファイルの6行目(空行 "\ n")になります。これはまだ起こっていません。あなたのエラーの場合のように、最初のレコードがあなたの検索と一致しないとします。あなたのコードによって実行される次のreadline()は:

days_in_hospital = int(file.readline()) 

そして、空白行から整数を作ることを試みるエラーを投げます。ですから、必要なのは、その空白行をスキップするための特別なreadline()です。

第2の問題は、ループが再び開始する前に、変数「レコード」が実際に次の行に移動しないということです。もう一度whileループを実行すると、レコードは "John Wilson"と等しくなります。

ですから、このような何か行うことができます:

  #determine if this record matches the search value 
      if record==searchName: 
       print("Name: " ,searchName) 
       print("Days in Hospital: " , days_in_hospital) 
       print("Daily Rate: " , daily_rate) 
       print("Service Charges: " , service_charge) 
       print("medication_Charges: " , medication_charges) 
       print("Total Charges: " ,total_charges) 
       print() 
       #set the found flag to True 
       found = True 
      else: 
       file.readline() #skip the blank line 
       record = file.readline() #read the next record 
関連する問題