0

我想从文件(.txt 或 .out)中读取包含特殊字符的字符串值的多维列表。然后我必须读取第一行的第一个值并与同一行的第二个值进行比较。

像:

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

我的问题是如何提取这些价值。值必须以这种格式读取 - <"this">

我尝试拆分/加入,但无法获得确切的一个字符串(要么给出整行,要么逐个字符拆分)

4

3 回答 3

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:另一种方式 - 使用 '["(.*?)"' 之类的正则表达式 - 它会匹配任何以 "[" 开头的字符串,后跟不带分隔符的双引号字符。之后,我用另一个双引号符号指定了非贪婪模式和封闭表达式。不确定这会是更可取的方法,但它确实发生了。

于 2013-04-04T11:02:51.727 回答
0

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

使用 Python JSON 模块对其进行解码:

with open('Path/to/file', 'r') as content_file:
    content = content_file.read()
    data = json.loads(content)
于 2013-04-04T11:49:13.763 回答
0
>>> import ast
>>> text = '''[
        ["this", "why this7656^"],
        ["@this", "whAy @this code"],
        ["is ", "this@@#@# code is complex"],
        ["@#@#", "Test@#@#his Test"]
    ]'''
>>> ast.literal_eval(text)
[['this', 'why this7656^'], ['@this', 'whAy @this code'], ['is ', 'this@@#@# code is complex'], ['@#@#', 'Test@#@#his Test']]
于 2013-04-04T12:05:41.627 回答