2017-04-07 54 views
0

當我在一個txt文件這樣寫着:打開項目從一個字符串列表中

with open("sample.txt") as f: 
content = f.readlines() 
for row in content: 
    print(row) 

我有以下輸入:

['k'], ['m'] 

我想變成這樣:

[k, m] 

因此,因此我嘗試

with open("sample.txt") as f: 
content = f.readlines() 
for row in content: 
    items = items.replace('\'', '') for item in items 
    row_analyze = ','.join(items) 

然而,這給了我:

[,,k,,],,,[,,m,,], 

任何思考我做錯了什麼在這裏?

+2

什麼數據真的包含在文件中? –

+0

'items = items.replace('\'','')for item in items'沒有意義。你的意思是'items = [item.replace('\'','')for item in row]'? –

+0

回過頭來,''sample.txt''從哪裏來?也許你可以通過'pickle'或者'json'模塊來避免這個中間文件或者把它作爲python對象正確保存 –

回答

0

刺痛['k'], ['m'],實際上代表名單,你可以簡單地將其轉換爲一個Python元組對象使用ast.literal_eval()功能的元組,那麼連鎖使用itertools.chain()功能列表:

In [1]: s = "['k'], ['m']" 

In [2]: import ast 

In [3]: ast.literal_eval(s) 
Out[3]: (['k'], ['m']) 

In [4]: from itertools import chain 

In [6]: list(chain.from_iterable(ast.literal_eval(s))) 
Out[6]: ['k', 'm'] 
+0

請注意,OP似乎希望''k,m]'的輸出沒有''' –

0

好像你row是字符串"['k'], ['m']"。如果您想將其轉換爲"[k, m]",則一些簡單的replace語句就足夠了。首先,刪除',但接着用,而不是join字符串中的字符,用,替換剩下的] ,[

>>> row = "['k'], ['m']" 
>>> row.replace("'", '') 
'[k], [m]' 
>>> row.replace("'", "").replace("], [", ", ") 
'[k, m]' 
相關問題