简体   繁体   English

解析文本文件时出错-Python

[英]Error parsing text file - Python

I have a text file with fields of names associated with numbers. 我有一个文本文件,其名称字段与数字关联。 The fields are separated by a blank line. 字段由空白行分隔。 The code should deliver the selected name and its associated fields. 该代码应提供选定的名称及其相关字段。 Here is my stacktrace: 这是我的堆栈跟踪:

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'

I'm providing my code and the text file: 我正在提供我的代码和文本文件:

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()        

main() 主要()

Here is the text file: 这是文本文件:

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

Also, if I enter any name other than the first one which is John Wilson, I get the following error: 另外,如果我输入的名字不是约翰·威尔逊(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'

You had logic errors in your code that prevented a smooth interaction with the user. 您的代码中存在逻辑错误,导致无法与用户顺利进行交互。 (Eg, your handling of the record name, the blank line between records, when the file was closed, etc.) I've reworked your logic, see if this gives you the result you're looking for: (例如,您对记录名称的处理,记录之间的空白行,文件关闭的时间,等等。)我重新设计了您的逻辑,看看是否能为您提供所需的结果:

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()

You are reading your file line by line and the format assumed by the code does not match the actual file. 您正在逐行读取文件,并且代码假定的格式与实际文件不匹配。

Your first readline() grabs the first line of the file ("John Wilson"), then in your loop you do 4 more readline() to get all the numbers on the following lines. 您的第一个readline()会抓住文件的第一行(“ John Wilson”),然后在循环中再执行4个readline()来获取下一行的所有数字。

At this point, the next readline() will take line 6 of your file (the blank line "\\n"). 此时,下一个readline()将占据文件的第6行(空白行“ \\ n”)。 This hasn't happened yet though. 不过这还没有发生。 Assume the first record does not match your search as in your error case. 假定第一个记录与您的搜索不匹配,就像在错误情况下一样。 The next readline() executed by your code is: 您的代码执行的下一个readline()是:

days_in_hospital = int(file.readline())

And it throws the error trying to make a integer out of a blank line. 并尝试从空行中生成整数时引发错误。 So what you need is an extra readline() in your loop to skip that blank line. 因此,您需要在循环中添加一个readline()来跳过该空白行。

Second problem is that that your variable "record" isn't actually moved to the next line before the loop starts again. 第二个问题是,在循环再次开始之前,您的变量“ record”实际上并未移至下一行。 The second time your while loop is executed, record still equals "John Wilson". 第二次执行while循环时,记录仍然等于“ John Wilson”。

So you could do something like this: 因此,您可以执行以下操作:

           #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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM