如何在python中创建一个dict列表,并从文本文件中读取数据?

时间:2012-03-13 00:00:32

标签: python list dictionary

我正在尝试使用莎士比亚的十四行诗来创建一个词典列表。

我想创建这样的东西:

list [0] =='Sonnet 1',如何让'Sonnet 1'成为真正的十四行诗的关键?

http://www.shakespeares-sonnets.com/sonnet/1了解有关十四行诗的更多信息。

我将十四行诗以这种格式保存到文件中:

SONNET 1

我们渴望增加最公平的生物, 因此,美丽的玫瑰可能永远不会死, 但随着时间的推移,应该逐渐减少, 他温柔的继承人可能会记住他的记忆: 但是,你收缩了自己明亮的眼睛, 用自给自足的燃料喂你的光芒, 在丰富的地方制造饥荒, 你自己的敌人,你的甜蜜自我太残忍了。 你现在的艺术世界是新鲜的装饰品 只有这个华丽的春天, 在你自己的萌芽中最内容 并且,温柔的churl,在niggarding中浪费。 可怜世界,否则这个贪食者, 要通过坟墓和你来吃世界。

SONNET 2

当四十个冬天来到你的额头时, 在你美丽的领域挖掘深壕, 你年轻时自豪的制服,现在凝视着, 将是一个破烂的杂草,小的价值举行: 然后问你所有的美丽在哪里, 你渴望的日子里所有的宝藏, 要说,在你自己深陷的眼睛里, 是一种无所谓的羞耻和无节制的赞美。 还有多少赞美值得你的美丽使用, 如果你能回答'我这个公平的孩子 应该算上我的数,并找出我的旧借口,' 你的继承证明了他的美丽! 当你老了,这是新的, 当你感到寒冷时,看到你的血液温暖。

依旧......

最初我使用split(“\ n \ n”),因此列表看起来像['Sonnet 1','sonnet 1的内容','Sonnet 2','sonnet 2的内容',... ]

然后,我使用for循环来(尝试)制作list [0] == ['title']:'Sonnet 1',['sonnet']:'sonnet 1'的内容],列表[1 ]将是十四行诗2,等等..

3 个答案:

答案 0 :(得分:2)

听起来你只想要一个普通的旧dict,而不是一个字典列表。

sonnet = '''From fairest creatures we desire increase,
That thereby beauty's rose might never die,
But as the riper should by time decease,
His tender heir might bear his memory:
But thou contracted to thine own bright eyes,
Feed'st thy light's flame with self-substantial fuel,
Making a famine where abundance lies,
Thy self thy foe, to thy sweet self too cruel:
Thou that art now the world's fresh ornament,
And only herald to the gaudy spring,
Within thine own bud buriest thy content,
And, tender churl, mak'st waste in niggarding:
Pity the world, or else this glutton be,
To eat the world's due, by the grave and thee.'''

# create with dict constructor
shakespeares_sonnets = {'Sonnet 1': sonnet, 'Sonnet 2': 'etc....'}

# add new ones later
shakespeares_sonnets['Sonnet N'] = 'Yo dawg, I herd u like sonnets...'

# easy to make lists out of the dict
list_of_sonnet_titles = shakespeares_sonnets.keys()
list_of_sonnets = shakespeares_sonnets.values()

答案 1 :(得分:2)

据我所知,你真的需要一个简单的dict

my_sonnets = {}
my_sonnets['Sonnet 1'] = 'The sonnet text'

如果你仍然确定你需要一个dicts列表(其中每个dict代表一个具有多个“属性”的单个sonnet,如title / text / author / etc),那么我强烈建议你考虑一个类。

class Sonnet(object):
    def __init__(self, title, text='', author=''):
        self.title = title
        self.text = text
        self.author = author

#Create a sonnet and set the author later
sonnet1 = Sonnet('Sonnet #1', 'Some text')
sonnet1.author = 'Mr. Bob'

#Create a sonnet specifying all fields
sonnet2 = Sonnet('Sonnet #2', 'Some other text', 'Ms. Sally')

#Creating a list from the sonnets above
my_list = [sonnet1, sonnet2]


#Alternatively, create the list in place
my_list = [Sonnet('Sonnet #1', 'Some text'), Sonnet('Sonnet #2', 'Some other text', 'Ms. Sally')]
#Set the author on the first item after the fact if you so choose
my_list[0].author = 'Mr. Bob'

最后,如果您已经开始使用错误的数据结构来处理所述问题......

my_list = [{'title':'Sonnet1', 'text':'Blah'}, {'title':'Sonnet2', 'text':'more blah', 'author':'Ms. Sally'}]
my_list[0]['author'] = 'Mr. Bob'

答案 2 :(得分:2)

使用此技巧迭代分裂成对的结果

zip(*[iter(sonnets.split("\n\n"))]*2)

例如

>>> sonnets = "SONNET 1\n\nFrom fairest creatures we desire increase, That thereby beauty's rose might never die, But as the riper should by time decease, His tender heir might bear his memory: But thou, contracted to thine own bright eyes, Feed'st thy light's flame with self-substantial fuel, Making a famine where abundance lies, Thyself thy foe, to thy sweet self too cruel. Thou that art now the world's fresh ornament And only herald to the gaudy spring, Within thine own bud buriest thy content And, tender churl, makest waste in niggarding. Pity the world, or else this glutton be, To eat the world's due, by the grave and thee.\n\nSONNET 2\n\nWhen forty winters shall beseige thy brow, And dig deep trenches in thy beauty's field, Thy youth's proud livery, so gazed on now, Will be a tatter'd weed, of small worth held: Then being ask'd where all thy beauty lies, Where all the treasure of thy lusty days, To say, within thine own deep-sunken eyes, Were an all-eating shame and thriftless praise. How much more praise deserved thy beauty's use, If thou couldst answer 'This fair child of mine Shall sum my count and make my old excuse,' Proving his beauty by succession thine! This were to be new made when thou art old, And see thy blood warm when thou feel'st it cold."
>>> L=[{'title':title, 'content': content} for title, content in zip(*[iter(sonnets.split("\n\n"))]*2)]
>>> L[0]['title']
'SONNET 1'
>>> L[0]['content']
"From fairest creatures we desire increase, That thereby beauty's rose might never die, But as the riper should by time decease, His tender heir might bear his memory: But thou, contracted to thine own bright eyes, Feed'st thy light's flame with self-substantial fuel, Making a famine where abundance lies, Thyself thy foe, to thy sweet self too cruel. Thou that art now the world's fresh ornament And only herald to the gaudy spring, Within thine own bud buriest thy content And, tender churl, makest waste in niggarding. Pity the world, or else this glutton be, To eat the world's due, by the grave and thee."
>>> L[1]['title']
'SONNET 2'
>>> L[1]['content']
"When forty winters shall beseige thy brow, And dig deep trenches in thy beauty's field, Thy youth's proud livery, so gazed on now, Will be a tatter'd weed, of small worth held: Then being ask'd where all thy beauty lies, Where all the treasure of thy lusty days, To say, within thine own deep-sunken eyes, Were an all-eating shame and thriftless praise. How much more praise deserved thy beauty's use, If thou couldst answer 'This fair child of mine Shall sum my count and make my old excuse,' Proving his beauty by succession thine! This were to be new made when thou art old, And see thy blood warm when thou feel'st it cold."