用python对文本文件排序

2024-05-15 13:35:59 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有一个文本文件,其中的配方如下:

TITLE: Michigan Pie:

INGREDIENTS: 8 oz cream cheese 1 can sweetened, condensed milk ¼ c lemon juice 15 oz crushed pineapple 8 oz whipped cream

DIRECTIONS: Drain the pineapple very well. Beat the cream cheese until it’s very smooth. Add the sweetened, condensed milk a little bit at a time. Mix in the lemon juice and pineapple. Fold in the whipped cream. Pour the mixture into two graham cracker pie crusts and refrigerate.

我怎么能用Python把所有的标题,所有的成分放在一起等等。。。??在


Tags: andtheinveryjuicelemon文本文件cream
3条回答

1)加载所有文件,对其进行解析,然后放入词典列表中

2)按您想要的方式对列表进行排序(请参见How do I sort a list of dictionaries by values of the dictionary in Python?

用三个键初始化字典。在

解析文本文件。只要找到其中一个键,就将它下面的文本添加到字典中相应的键值对中。当您看到另一个粗体键时停止并继续解析。在

例如,如果您想要一个标题列表,而不仅仅是一个长的、长的、长的字符串,那么可以使用一个包含列表的字典。在

例如

data = {'TITLE':[], 'INGREDIENTS':[], 'DIRECTIONS':[]}

将解析后的数据追加到列表中。在

假设配方列表在recipe.txt中,并且标题总是用冒号分隔,那么下面的代码就可以得到字典了。在

with open('recipe.txt') as recipe:
  g = ( line.split(':',1) for line in recipe )
  g = ( (i[0],i[1:]) for i in g if len(i)>1 )
  d = dict()
  for k,v in b:
    d[k] = d.get(k,[]) + v

不过,你现在喜欢。在

相关问题 更多 >