Python字符串列表处理

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'文件的格式而不更改内容 - 这是为了给您一些灵活性。

谢谢:)

+0

为什么不坚持使用经典格式,只使用ConfigParser? –

+0

@Raymond感谢您通知有关configparser,我会研究它。 – Ani

+0

@AnimeshSharma我喜欢配置者的答案,无论如何,我建议你如何使用你的格式来做 – lc2817

如果使用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

如果你希望你的应用程序敬了一个标准你可能有兴趣在ConfigParser module.

您可以重写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 
+0

更好地习惯于不使用'list'作为变量名,它隐藏了内置的元素并且可能导致难以调试错误。 – mkriheli

+0

谢谢,我在发布答案后重新编辑。 –

+0

感谢Alvin为你准备。现在我知道两个解决方案,我的问题:) – Ani