从文本文件加载Python集合 [英] Loading a Python collection from an text-file

查看:53
本文介绍了从文本文件加载Python集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在python脚本中,我喜欢创建一个集合,我用外部文本文件(用户可编辑的)填充

值。


如何实现这是最简单的方法(如果可能的话,不需要

的库不属于标准发行版)?


类似于:


文本文件:

{peter,16},

{anton,21}


-


代码内:


users.load(text-file.txt)


供用户使用

user.name

user.age


..

-
http://lazaridis.com

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

..

--
http://lazaridis.com

推荐答案

Ilias Lazaridis在python脚本中写道:
Ilias Lazaridis wrote:
,我喜欢创建一个我用值填充的集合外部文本文件(用户可编辑)。

如何完成e最简单的方法(如果可能的话,不需要图书馆不属于标准版的图书馆)?

类似的东西:

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

.



这是特定于上面的文字。如果实际文件不同,你将不得不重新制作正则表达式




导入重新


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 regex
if the actual file is different.

import re

def get_names(afile):
regex = re.compile(r''{([^,]*),\s*([^}]*)}'')
names = []
for aline in afile:
m = regex.search(aline)
names.append(m.groups())
return names

def test():
import cStringIO
afile = 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 spreadsheet
which saves the data in a simple xml format. xml is much less
error-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 would
separate 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 tab
Jonny 8
Mary 87
Moses 449
# end-snip ''text-file.txt''
Then:
"""

import string

class user:
def __init__(self,name,age):
self.name=name
self.age=int(age) # or a float, or a time-interval, or date-of-birth

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()
for L0 in Lines:
L1=string.strip(L0)
if not L1.startswith("#"):
Record=string.split(L1,fieldsep)
# insert error handling/validation here
users.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) is
to use python syntax (a dictionary, say, or a list) and just import (or
reload) the file


这篇关于从文本文件加载Python集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆