2011-11-21 67 views
2

我覺得我最近獲得的知識仍然不足以處理字符串。請幫我解決以下問題陳述: (請注意:這是我的要求的簡化版本)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

回答

5

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

1

您可以重寫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'] 
2

這裏有一個簡單的答案:

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