[英]how do i create a list of dict in python with the data been read from a text file?
I am trying to create a list of dictionaries using shakespeare's sonnets. 我正在尝试使用莎士比亚的十四行诗创建词典列表。
I want to create something like this: 我想创建这样的东西:
list[0] == 'Sonnet 1', how do I get 'Sonnet 1' to be the key of the actual sonnet? list [0] =='Sonnet 1',我如何让'Sonnet 1'成为实际十四行诗的钥匙?
http://www.shakespeares-sonnets.com/sonnet/1 for more info on sonnets. 有关十四行诗的更多信息, 请http://www.shakespeares-sonnets.com/sonnet/1 。
I saved the sonnets into a file in this format: 我将十四行诗保存为以下格式的文件:
SONNET 1 十四行诗1
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.
您现在已成为世界上最新鲜的装饰品,并且只预示着艳丽的春天,在您自己的芽中,您的内容最饱满,而柔嫩的缩,却使ni废。 Pity the world, or else this glutton be, To eat the world's due, by the grave and thee.
怜悯世界,否则this嘴,要吃坟墓和你的世界应得的。
SONNET 2 十四行诗
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.
当你年老时,这将是新的。当你感到寒冷时,看看你的血液是温暖的。
and so on... 等等...
initially I used split("\\n\\n"), so the list would look like ['Sonnet 1', 'content of sonnet 1', 'Sonnet 2', 'content of sonnet 2', ...] 最初我使用split(“ \\ n \\ n”),所以列表看起来像['Sonnet 1','Sonnet 1的内容','Sonnet 2','Sonnet 2'的内容,...]
then, I use a for loop to (try to) make list[0] == ['title'] : 'Sonnet 1',['sonnet'] : 'content of sonnet 1'], list[1] will be of sonnet 2, and so on.. 然后,我使用一个for循环来(尝试)制作list [0] == ['title']:'Sonnet 1',['sonnet']:'sonnet 1的内容'],list [1]将是十四行诗2,依此类推..
It sounds like you just want a plain old dict
, not a list of dictionaries. 听起来您只想要一个普通的老
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()
From what I can tell, you really just need a simple dict
从我可以告诉,你真的只需要一个简单的
dict
my_sonnets = {}
my_sonnets['Sonnet 1'] = 'The sonnet text'
If you're still certain you want a list of dicts (where each dict is representing a single sonnet with multiple "attributes" like title/text/author/etc), then I strongly urge you to consider a class instead. 如果仍然可以确定词典列表(每个词典代表一个带有多个“属性”(如标题/文本/作者/等)的十四行诗),那么我强烈建议您考虑使用一类。
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'
Finally, if you're dead set on using the wrong data structure for the stated question... 最后,如果您不愿意为所提出的问题使用错误的数据结构...
my_list = [{'title':'Sonnet1', 'text':'Blah'}, {'title':'Sonnet2', 'text':'more blah', 'author':'Ms. Sally'}]
my_list[0]['author'] = 'Mr. Bob'
Use this trick to iterate through the results of the split pairwise 使用此技巧来逐对拆分结果进行迭代
zip(*[iter(sonnets.split("\n\n"))]*2)
eg. 例如。
>>> 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."
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.