值填充的集合外部文本文件(用户可编辑)。 这是特定于上面的文字。如果实际文件不同,你将不得不重新制作正则表达式 。 导入重新 def get_names(afile): regex = re.compile(r''{([^,] *),\ * *([^}] *)}'') names = [] for aline in afile: m = regex.search(aline) names.append(m .groups()) 返回名称 def test(): import cStringIO afile = cStringIO.StringIO(" {peter,16},\ n {anton,21} \ n") print get_names(afile) test()This is specific for the text above. You will have to re-craft a regexif the actual file is different.import redef get_names(afile):regex = re.compile(r''{([^,]*),\s*([^}]*)}'')names = []for aline in afile:m = regex.search(aline)names.append(m.groups())return namesdef test():import cStringIOafile = cStringIO.StringIO("{peter, 16},\n{anton, 21}\n")print get_names(afile)test() Ilias Lazaridis在python脚本中写道:Ilias Lazaridis wrote:,我喜欢创建一个我填的集合来自外部文本文件的值(用户可编辑)。 如何以最简单的方式完成(如果可能的话,不需要图书馆不属于标准分发)? 类似的东西: text-file: {peter,16}, {anton,21} 代码内: users.load( text-file.txt) 用户中的用户 user.name user.age 。 within a python script, I like to create a collection which I fill with values from an external text-file (user editable). How is this accomplished the easiest way (if possible without the need of libraries which are not part of the standard distribution)? something like: text-file: {peter, 16}, {anton, 21} - within code: users.load(text-file.txt) for user in users user.name user.age . """ 我为这类工作做的是使用一个数字电子表格 ,它以简单的xml格式保存数据。与普通文本相比,xml更不容易出错。 Google为David Gilbert研究''gnumeric文件格式'。 您需要知道如何解压缩文件,以及如何编写SAX解析器。 如果您想使用纯文本格式,请保持简单。我将 用tab分隔两个字段(因此允许字段中的逗号) 并允许以哈希开头的注释行。 你不需要大括号或你所包含的行尾逗号。 #snip''text-file.txt'' #一行分隔的名称和年龄 强尼8 玛丽87 摩西449 #end-snip''text-file.txt'' 然后: """ 导入字符串 类用户: def __init __(自我,姓名,年龄): self.name =姓名 self.age = int(年龄)#或浮动,或时间间隔,或出生日期 def show(self ): print"%s is aged%s" %(self.name,self.age) if __name __ ==" __ main __": users = [] filename =" text-file.txt" fieldsep =" \t" F = open(filename," r") Lines = F.readlines()行中L0的: L1 = string.strip(L0)如果不是 L1.startswith(#): Record = string.split(L1,fieldsep) #在这里插入错误处理/验证 users.append(用户(记录[0],记录[1])) F.close() 用户中的用户: user.show()"""What I do for this kind of work is to use a gnumeric spreadsheetwhich saves the data in a simple xml format. xml is much lesserror-prone than plain text.Google for, and study ''The gnumeric file format'' by David Gilbert.You need to know how to unzip the file, and how to write a SAX parser.If you want to use a plain text format, keep it simple. I wouldseparate the two fields with tab (thus permit a comma within a field)and allow ''comment'' lines that start with a hash.You don''t need the braces, or the end-of-line comma you included.# snip ''text-file.txt''# name and age on one line separated by tabJonny 8Mary 87Moses 449# end-snip ''text-file.txt''Then:"""import stringclass user:def __init__(self,name,age):self.name=nameself.age=int(age) # or a float, or a time-interval, or date-of-birthdef show(self):print "%s is aged %s" % (self.name, self.age)if __name__=="__main__":users=[]filename="text-file.txt"fieldsep="\t"F=open(filename,"r")Lines=F.readlines()for L0 in Lines:L1=string.strip(L0)if not L1.startswith("#"):Record=string.split(L1,fieldsep)# insert error handling/validation hereusers.append(user(Record[0],Record[1]))F.close()for user in users:user.show()另一种方法(可能不赞成,但它对我有用)是 使用python语法(字典,比如说或列表),然后导入(或 重新加载)文件another approach (probably frowned upon, but it has worked for me) isto use python syntax (a dictionary, say, or a list) and just import (orreload) the file 这篇关于从文本文件加载Python集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 09-02 12:23