2013-04-04 79 views
0

我想讀取包含文件(.txt或.out)中的特殊字符的多維列表值。 然後,我必須讀取第一行的第一個值,並與同一行的第二個值進行比較。從文件讀取多維列表字符串數組

像:

[ 
     ["this","why this7656^"] 
     ["@this","whAy @this code"], 
     ["is ", "[email protected]@#@# code is complex"], 
     ["@#@#", "[email protected]#@#his Test"] 
    ] 

我的問題是,如何提取這些值。 值必須在這個格式讀取 - <「這個」>

我試圖分裂/加入,但無法得到確切的一個字符串(它給整行或字符的字符分割它)

回答

0

您的示例字符串看起來像JSON

使用Python JSON Module將其解碼:

with open('Path/to/file', 'r') as content_file: 
    content = content_file.read() 
    data = json.loads(content) 
+0

是的它看起來像JSON,但我需要知道的文本文件,然後我會移動到_JSON_和JSON給出這樣的結果 [[u'this',u'why this7656 ^'],[u'@這',u'whAy @此代碼'],[u'is',u'this @@#@#code is complex'],[u'@#@#',u'Test @#@#他的測試']] – KumarDharm 2013-04-04 13:05:24

+0

如何用python做到這一點<2.5 – KumarDharm 2013-04-05 12:16:21

+0

你的第一條評論的結果有什麼問題?這對我來說似乎是正確的。對於Python 2.4安裝simplejson 2.1.0:https://pypi.python.org/pypi/simplejson/2.1.0 – johnbaum 2013-04-05 16:35:34

0

這是不好的做法 - 使用'eval' - 但它是解決您的問題最簡單的方法。您只有必須保證您將評估的聲明是安全正確的Python代碼。試試這個:

with open('Path/to/file', 'r') as content_file: 
    content = content_file.read() 
    data = eval(content) 
    print ['<%s>' % x[0] for x in l] 

檢索Python的收集後,我希望這將不是一個問題,提取所需的數據項爲您服務。

UPD:另一種方式 - 使用正則表達式,如「[‘(*?)’」 - 它將匹配從而拉開了「[」,不分離的雙引號字符以下的字符串。之後,我用另一個雙引號符號指定了非貪婪模式和閉合表達式。不知道這將是更可取的方法,但它發生。

+0

'代碼' 張開( 「d:\\ ReadData.txt」, 「R」)作爲content_file: 含量= content_file。閱讀() 數據= EVAL(內容) 打印數據 回溯(最近通話最後一個): 數據= EVAL(內容) 文件 「」,3號線,在 TypeError:列表索引必須是整數,而不是元組 – KumarDharm 2013-04-04 11:12:56

+0

它看起來像在'[「this」後面忘記了逗號,「爲什麼是this7656 ^」]'。該代碼是否由第三方服務提供 - 無逗號? – 2013-04-04 11:15:16

+0

對不起我的錯誤(它工作) – KumarDharm 2013-04-04 11:16:39

0
>>> import ast 
>>> text = '''[ 
     ["this", "why this7656^"], 
     ["@this", "whAy @this code"], 
     ["is ", "[email protected]@#@# code is complex"], 
     ["@#@#", "[email protected]#@#his Test"] 
    ]''' 
>>> ast.literal_eval(text) 
[['this', 'why this7656^'], ['@this', 'whAy @this code'], ['is ', '[email protected]@#@# code is complex'], ['@#@#', '[email protected]#@#his Test']] 
+1

這也會給出相同的結果嗎? '進口string' '具有開放( 「d:\\ ReadData.txt」)爲f:'' 線= f.readline()'' 打印line' – KumarDharm 2013-04-04 13:12:51