-2

現在、ファイルから次の情報を入力するプロジェクトに取り組んでいます。

10015, John, Smith, 2, 3.01
10208, Patrick, Green, 1, 3.95
10334, Jane, Roberts, 4, 3.81

私がする必要があるのは、この情報を分割し、各値を個別に保存してから、ユーザーのニーズに基づいて画面またはファイルに出力することです。

情報を分割して割り当てる関数は次のとおりです。

def fetchRecord( self ):
    #Read the first line of the record.
    line = self._inputFile.readline()
    line = input.split( ', ' )
    if line == "":
        return None

    #If there is another record, create a storage object and fill it
    student = StudentRecord()
    student.idNum = int( line[0] ) 
    student.firstName = line[1]
    student.lastName = line[2]
    student.classCode = int( line[3] )
    student.gpa = float( line[4] )
    return student

現在発生しているエラーは次のとおりです。

builtins.ValueError: invalid literal for int() with base 10: '10015, John, Smith, 2, 3.01\n'

私が呼び出しているコード全体は次のとおりです。

class StudentFileReader:
#Create new student reader instance.
def __init__( self, inputSrc ):
    self._inputSrc = inputSrc
    self._inputFile = None

#Open a connection to the input file.
def open( self ):
    self._inputFile = open( self._inputSrc, "r" )

#Close the connection to the input file.
def close( self ):
    self._inputFile.close()
    self._inputFile = None

#Extract all student records and store them in a list.
def fetchAll( self ):
    theRecords = list()
    student = self.fetchRecord()
    while student != None:
        theRecords.append( student )
        student = self.fetchRecord()
    return theRecords

#Extract the next stuent record from the file.
def fetchRecord( self ):
    #Read the first line of the record.
    line = self._inputFile.readline()
    print ( line )
    line = line.split( ',' )
    print ( line )
    if line == "":
        return None

    #If there is another record, create a storage object and fill it
    student = StudentRecord()
    student.idNum = int( line[0] ) 
    student.firstName = line[1]
    student.lastName = line[2]
    student.classCode = int( line[3] )
    student.gpa = float( line[4] )
    return student


class StudentScreenWriter:
    #Prints the student report to screen.
    def printReport( theList ):
         #The class names associated with the class codes.
         classNames = ( None, "Freshman", "Sophomore", "Junior", "Senior" )

        #Print the header.
        print( "LIST OF STUDNETS".center(50) )
        print( "" )
        print( "%-5s %-25s %-10s %-4s" % ('ID', 'NAME', 'CLASS', 'GPA' ) )
        print( "%5s %25s %10s %4s" % ('-' * 5, '-' * 25, '-' * 10, '-' * 4) )

        #Print the body.
        for record in theList:
            print( "%5d %-25s %-10s %4.2f" % (record.idNum, record.lastName + ", " + record.firstName, classNames[record.classCode], record.gpa) )

        #Add a footer.
        print( "-" * 50 )
        print( "Number of students:", len(theList) )

class StudentFileWriter:
    #Prints the student report to file.
    def printReport( theList, out ):
        for record in theList
            record.idNum = str(record.idNum)
            record.lastName = str(record.lastName)
            record.firstName = str(record.firstName)
            record.classCode = str(record.classCode)
            record.gpa = str(record.gpa)

            out.write( record.idNum + ", " + record.lastName + ", " + record.firstName + ", " + record.classCode + ", " + record.gpa )
        out.write( "\n" )


class StudentRecord:
    def __init__( self ):
        self.idNum = None
        self.firstName = None
        self.lastName = None
        self.classCode = None
        self.gpa = None
4

3 に答える 3

4

あなたが探している答えではありませんが、考慮すべきです

class StudentRecord:
     def __init__(self,idNum=-1,firstName="unknown",lastName="Unknown",classCode=-1,gpa=-1):
         self.idNum = idNum
         self.firstName = firstName
         self.lastName = lastName
         self.classCode = classCode
         self.gpa = gpa
     #... The rest of your class

csvモジュールで

import csv
with open("some.txt") as f:
    reader = csv.reader(f)
    for student_details in reader:
        student = StudentRecord(*student_details)

csv モジュールなし

with open("some.txt") as f:
    for line in f:
        student_details = line.split(",")
        student = StudentRecord(*student_details)

データを使ったテスト

class StudentRecord:
    def __init__(self,idNum=-1,firstName="unknown",lastName="Unknown",classCode=-1,gpa=-1):
        self.idNum = idNum
        self.firstName = firstName
        self.lastName = lastName
        self.classCode = classCode
        self.gpa = gpa
    def  __str__(self):
        return "#%s:%s, %s | %s = %s"%(
            self.idNum,self.lastName,self.firstName,
            self.classCode,self.gpa
            )
    def __repr__(self):
        return "<Student Record (%s %s)>"%(
            self.firstName,self.lastName
            )

with open("txt_data.txt") as f:
    for line in f:
        student_data = line.strip().split(", ")
        student = StudentRecord(*student_data)
        print "Student:",student

出力:

Student: #10015:Smith, John | 2 = 3.01
Student: #10208:Green, Patrick | 1 = 3.95
Student: #10334:Roberts, Jane | 4 = 3.81
于 2013-01-11T04:25:44.560 に答える
2

行を変更する必要があります

 line = input.split( ', ' )

line = line.split( ',' )

後に移動します

if line == "":
    return None    

input現在のコンテキストでは定義されていません。

于 2013-01-11T04:14:20.373 に答える
0

データを分割するためにこれを考慮することができます(データを使用)

>>> for line in f:  
        li1 = []  
        for part in line.split(','):  
                part = part.strip()  
                li1.append(part)  
        li2.append(li1)  

>>> for i in li2:
        print i
['10015', 'John', 'Smith', '2', '3.01']  
['10208', 'Patrick', 'Green', '1', '3.95']  
['10334', 'Jane', 'Roberts', '4', '3.81']  

li1li2リストです。Andfは、各行にレコード/データがある入力ファイルです。

これでリストが表示されます。同じメソッドを使用して、名前、クラス コード、gpa などを取得して処理できます。

于 2013-01-11T07:43:40.010 に答える