0

导入文件后,打开并阅读

fop = open('lottery.txt','r')
_str = fop.read()
fop.close()

我得到这样的内容:

'   monday: 2 23\ntuesday :4 31\nwednesday   : 19 22\nthursday : 1'

如何将其转换为字典并得到以下结果:

{'monday': '2 23', 'tuesday': '4 31','wednesday': '19 22', 'thursday' : '1'}
4

1 回答 1

4

逐行处理:

with open('lottery.txt', 'r') as fop:
    result = dict(map(str.strip, line.split(':', 1)) for line in fop)

dict(map(..) for line in fop)正在使用生成器表达式;我们遍历fop每一行,然后在我们找到的第一个冒号上将该行拆分为两个值:,并将剥离的结果存储为映射的键和值。

map(str.strip, line.split(':', 1))从分割线的每个部分的开头和结尾删除空格。本身将.split()拆分限制:为 1 个这样的字符,以防止:行上任何额外的冒号混淆dict构造函数,构造函数只需要(key, value)对。

演示:

>>> open('/tmp/lottery.txt', 'w').write('   monday: 2 23\ntuesday :4 31\nwednesday   : 19 22\nthursday : 1')
>>> with open('/tmp/lottery.txt', 'r') as fop:
...     result = dict(map(str.strip, line.split(':', 1)) for line in fop)
... 
>>> result
{'tuesday': '4 31', 'thursday': '1', 'wednesday': '19 22', 'monday': '2 23'}

长的非生成器表达式版本将是:

with open('lottery.txt', 'r') as fop:
    result = {}
    for line in fop:
        key, value = line.split(':', 1)
        result[key.strip()] = value.strip()
于 2012-10-27T14:35:14.793 回答