从文件读入字典的字符串的python列表

2024-09-29 23:17:30 发布

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

我在写代码:

#!/usr/bin/python
#ekadasi 2013
#sukhdev mohan
import datetime
import pickle
from time import strptime

def openfile(path, mode):
       return open(path, mode)

def closefile(obj):
       obj.close()

def retrivedata(pntr):
       date = {}
       linelst = []
       wordlst = []
       for line in pntr:
              for word in line.split():
                     wordlst.append(word)
              linelst.append(wordlst)
              wordlst = []
       return linelst


def dumpitall(obj, pntr):
       pickle.dump(obj, pntr)

def loaditall(srcpntr):
       return pickle.load(srcpntr)

date = datetime.date.today()
print "E K A D A S I  2 0 1 3 "
print "Today: %d - %d - %d" % (date.day, date.month, date.year)     

dates = {}
filepntr = openfile("ekadasi.txt", "r")
nlist = retrivedata(filepntr)
closefile(filepntr)
for nl in nlist:
       print nl
       temp = nl[0] + "-" + str(strptime(nl[1], '%B').tm_mon)
       print temp
       value = str(nl[2] + nl[3])
       dates = dict((temp, value))

print dates

我正在读一个文件,它有4列:日-月名称(2列,带空格),你可以读我读过它,然后放入一个列表。我的目标是创建一个类型为:day number of month:name的字典,但不知道为什么字典的顺序与文件和列表的顺序不同,例如: 第一个要素是 文件:1月8日xyz asd 列表:[['08','January','xyz','asd']。。。] 键:08-1 一切如期而至,但字典作为其他元素是第一位的,第一位是第二位的。。。我该怎么修?有没有更好的方法来编写这个代码,或者如何优化它?你知道吗

谢谢你们


Tags: inimportobjfordatereturndefnl
2条回答

应该是这样的:

如Uku Loskit所述,使用集合中的OrderedDict。而且,你不需要用那么多for循环,你只需要一个。使用string.format格式(),这是python3的主要风格。

import datetime
import collections
from time import strptime

date = datetime.date.today()
print "E K A D A S I  2 0 1 3 "
print "Today: {day} - {month} - {year}".format(
    day   = date.day,
    month = date.month,
    year  = date.year
)

dates = collections.OrderedDict()
with open('ekadasi.txt', 'r') as file_data:
    for line in file_data.readlines():
        if line:  # if line is not empty
            day, month, name1, name2 = line.split()
            temp = '{day}-{month}'.format(
                day = day,
                month = strptime(month, '%B').tm_mon
            )
            dates[temp] = str(name1 + name2)
print dates

字典值的顺序没有任何保证。改用OrderedDict

相关问题 更多 >

    热门问题