Python字符串列表处理
问题描述:
我觉得我最近获得的知识仍然不足以处理字符串。请帮我解决以下问题陈述: (请注意:这是我的要求的简化版本)Python字符串列表处理
所以..我有一个文件(myoption)与内容如下:
day=monday,tuesday,wednesday
month=jan,feb,march,april
holiday=thanksgiving,chirstmas
我Python脚本应该能够读取该文件,并处理读取信息,从而在最后我有如下三甲之列变量:
day --> ['monday','tuesday','wednesday']
month --> ['jan','feb','march','april']
holiday --> ['thanksgiving','christmas']
请注意: 按我的要求,在myoption文件内容格式应该是s imple。 因此,您可以自由修改'myoption'文件的格式而不更改内容 - 这是为了给您一些灵活性。
谢谢:)
答
如果使用the standard ConfigParser
module您的数据需要在INI file format,所以会是这个样子:
[options]
day = monday,tuesday,wednesday
month = jan,feb,march,april
holiday = thanksgiving,christmas
然后,你可以读取文件如下:
import ConfigParser
parser = ConfigParser.ConfigParser()
parser.read('myoption.ini')
day = parser.get('options','day').split(',')
month = parser.get('options','month').split(',')
holiday = parser.get('options','holiday').split(',')
+0
是否有**使用configparser将新数据追加到INI文件中?使用.set我可以添加数据,但它会覆盖旧文件。 因此,如果我将新数据附加到旧的INI文件 - 截至目前我必须添加新的和旧的数据,这需要额外的资源。 – Ani
答
您可以重写YAML文件或XML。 无论如何,如果你想让你的简单的格式,这应该一句话:
指定的文件数据:
day=monday,tuesday,wednesday
month=jan,feb,march,april
holiday=thanksgiving,chirstmas
我提出这个python脚本
f = open("data")
for line in f:
content = line.split("=")
#vars to set the variable name as the string found and
#[:-1] to remove the new line character
vars()[content[0]] = content[1][:-1].split(",")
print day
print month
print holiday
f.close()
输出是
python main.py
['monday', 'tuesday', 'wednesday']
['jan', 'feb', 'march', 'april']
['thanksgiving', 'chirstmas']
为什么不坚持使用经典格式,只使用ConfigParser? –
@Raymond感谢您通知有关configparser,我会研究它。 – Ani
@AnimeshSharma我喜欢配置者的答案,无论如何,我建议你如何使用你的格式来做 – lc2817