Python 从字符串创建列表,在逗号处拆分
我目前正在从事一个项目,该项目从一个文件中输入以下信息:Python 从字符串创建列表,在逗号处拆分,python,python-3.x,split,Python,Python 3.x,Split,我目前正在从事一个项目,该项目从一个文件中输入以下信息: 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
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
你需要换线
line = input.split( ', ' )
到
然后移动它
if line == "":
return None
输入在当前上下文中未定义。不是您要寻找的答案,但您应该考虑
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)
with open("some.txt") as f:
for line in f:
student_details = line.split(",")
student = StudentRecord(*student_details)
没有csv模块
import csv
with open("some.txt") as f:
reader = csv.reader(f)
for student_details in reader:
student = StudentRecord(*student_details)
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
>>> 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']
你可以考虑把数据拆分(使用你的数据)
li1
和li2
是列表。而f
是输入文件,其中每行都有一条记录/数据
现在您将获得列表。您可以使用相同的方法获取和处理名称、类代码、gpa等。应该是line.split(“,”),我认为逗号后不应该有空格。CSV文件由单个字符严格分隔。我这样说的原因是,分割队列将更安全,尤其是对于丢失的数据。i、 e.10015,John,Smith,,3.01
@KeyferMathewson:修复后发生了什么?请在拆分前打印行。。然后。。。把你的结果放在原稿上question@JoranBeasley出于某种原因,它甚至没有打印到外壳上。我将发布上面的全部代码。如果您正在重写并建议更好的解决方案,请建议使用csv
模块解析已编辑的csv文件。。。我想这就是你使用csv阅读器的方式:P。。。在我看来,csv.reader模块一直是一个典型的滥杀滥伤案例;对于这样一个简单的示例,您的代码从一行非常明显的代码(line.split(“,”)更改为一个方法调用,您必须尝试记住forthere:P now everyons的语法happy@sapi我个人认为,学习语法的成本远远超过了它内置的额外功能。例如,如果OP使用的是欧洲编号方案(使用3,85
而不是3.85
),则拆分将无法按预期工作(在带有逗号的字段中也无法工作)。