简体   繁体   English

从 python 中的文件中读取逗号分隔的元组

[英]Reading comma separated tuples from a file in python

I am trying to read from a file with several tuples separated by commas.我正在尝试从一个文件中读取几个用逗号分隔的元组。 A sample input file looks like:示例输入文件如下所示:

(0, 0), (0, 2), (0, 4), (-1, -1), (0, -2), (1, -1), (-1, -3), (0, 0), (0, 2), (0, 4), (-1, -1), (0, -2), (1, -1), (-1, -3),

(-1, 1), (-1, 3), (1, 1), (1, 3), (1, 5), (2, 0), (2, 2), (3, 3), (-1, 1), (-1, 3), (1, 1), (1, 3), (1, 5), (2, 0), (2, 2), (3, 3),

(2, 4), (3, 5), (4, 4), (5, 3), (6, 4), (5, 5), (7, 5) (2, 4), (3, 5), (4, 4), (5, 3), (6, 4), (5, 5), (7, 5)

After reading from this file, I need a tuple like this:从这个文件中读取后,我需要一个这样的元组:

G = ((0, 0), (0, 2), (0, 4), (-1, -1), (0, -2), (1, -1), (-1, -3), \
(-1, 1), (-1, 3), (1, 1), (1, 3), (1, 5), (2, 0), (2, 2), (3, 3), \
(2, 4), (3, 5), (4, 4), (5, 3), (6, 4), (5, 5), (7, 5))

How this can be done efficiently?如何有效地做到这一点? Regards.问候。

Since they look like proper python tuples you can use literal_eval . 因为它们看起来像正确的python元组,所以你可以使用literal_eval Its fast as safe: 它安全快捷:

Safely evaluate an expression node or a string containing a Python expression. 安全地评估表达式节点或包含Python表达式的字符串。 The string or node provided may only consist of the following Python literal structures: strings, numbers, tuples, lists, dicts, booleans, and None. 提供的字符串或节点可能只包含以下Python文字结构:字符串,数字,元组,列表,dicts,布尔值和None。

import ast
s = '''(0, 0), (0, 2), ...'''
result = ast.literal_eval('({0})'.format(s))

Assuming there is a file.txt with the following content: 假设有一个包含以下内容的file.txt

(0, 0), (0, 2), (0, 4), (-1, -1), (0, -2), (1, -1), (-1, -3)
(-1, 1), (-1, 3), (1, 1), (1, 3), (1, 5), (2, 0), (2, 2), (3, 3),
(2, 4), (3, 5), (4, 4), (5, 3), (6, 4), (5, 5), (7, 5)

You can use literal_eval() on each line in a loop and extend resulting list: 您可以在循环中的每一行上使用literal_eval()并扩展结果列表:

from ast import literal_eval

result = []
with open('file.txt', 'r') as f:
    for line in f:
        result.extend(literal_eval(line.strip()))

print result

prints: 打印:

[(0, 0), (0, 2), (0, 4), (-1, -1), (0, -2), (1, -1), (-1, -3), (-1, 1), (-1, 3), (1, 1), (1, 3), (1, 5), (2, 0), (2, 2), (3, 3), (2, 4), (3, 5), (4, 4), (5, 3), (6, 4), (5, 5), (7, 5)]

FYI, literal_eval() is safe: 仅供参考, literal_eval()是安全的:

Safely evaluate an expression node or a string containing a Python expression. 安全地评估表达式节点或包含Python表达式的字符串。 The string or node provided may only consist of the following Python literal structures: strings, numbers, tuples, lists, dicts, booleans, and None. 提供的字符串或节点可能只包含以下Python文字结构:字符串,数字,元组,列表,dicts,布尔值和None。

Hope that helps. 希望有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM