Python字符串到列表处理

Python字符串到列表处理,python,string,file,list,Python,String,File,List,我觉得我最近学到的关于字符串处理的知识还不够。请帮助我解决以下问题声明: (请注意:这是我要求的更简单版本) 所以。。我有一个文件(myoption),内容如下: day=monday,tuesday,wednesday month=jan,feb,march,april holiday=thanksgiving,chirstmas day --> ['monday','tuesday','wednesday'] month --> ['jan','feb','march','ap

我觉得我最近学到的关于字符串处理的知识还不够。请帮助我解决以下问题声明: (请注意:这是我要求的更简单版本)

所以。。我有一个文件(myoption),内容如下:

day=monday,tuesday,wednesday
month=jan,feb,march,april
holiday=thanksgiving,chirstmas
day --> ['monday','tuesday','wednesday']
month --> ['jan','feb','march','april']
holiday --> ['thanksgiving','christmas']
我的python脚本应该能够读取文件并处理读取的信息,这样最终我有三个列表变量,如下所示:

day=monday,tuesday,wednesday
month=jan,feb,march,april
holiday=thanksgiving,chirstmas
day --> ['monday','tuesday','wednesday']
month --> ['jan','feb','march','april']
holiday --> ['thanksgiving','christmas']
请注意: 根据我的要求,myoption文件中的内容格式应该简单。 因此,您可以自由修改“myoption”文件的格式,而无需更改内容-这是为了给您一些灵活性


谢谢:)

您可能对

感兴趣。如果希望应用程序遵守标准,您可以用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']

这里有一个简单的答案:

s = 'day=monday,tuesday,wednesday'
mylist = {}
key, value = s.split('=')
mylist[key] = value.split(',')

print mylist['day'][0]

Output: monday
如果您使用您的数据,则需要输入,因此会出现如下情况:

[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(',')

为什么不坚持使用经典格式,只使用ConfigParser?@Raymond感谢您告知ConfigParser,我会研究它。@AnimeshSharma我喜欢confiparser的答案,不管怎样,我建议您如何使用格式更好地习惯不使用
列表
作为变量名,它隐藏了内置代码,可能会导致难以调试的bug。谢谢,在我发布了答案后,我一直在想这个问题,重新编辑。谢谢阿尔文给我的时间。现在我知道了解决我问题的两种方法:)我主张将
ConfigParser
作为第一选择(即:尽可能不要重新发明轮子:)。是否仍然可以使用ConfigParser将新数据附加到INI文件中?使用.set我可以添加数据,但它会覆盖旧文件。因此,如果我将新数据附加到旧的INI文件中,那么现在我必须添加新的和旧的数据,这需要额外的资源。