python-用字符串填充字典

python-用字符串填充字典,python,string,dictionary,Python,String,Dictionary,我有一个由多行组成的字符串,每行包含一个键和一个对象的2个属性的2个值。我想将它们加载到字典中,字符串位于txt文件中。 我只能定义函数: def load_a_string(self, thestring): 下面是txt文件中的字符串(我想要的字符串从第四行开始): 从第4行开始,我想转换成dict。每个数字元组是dict中的一个键,另外两个是名为piece的类的实例(对象)的属性,“blanc”或“noir”是属性piece的值。“color”和“pion”是属性piece的值。类型(其

我有一个由多行组成的字符串,每行包含一个键和一个对象的2个属性的2个值。我想将它们加载到字典中,字符串位于txt文件中。 我只能定义函数:

def load_a_string(self, thestring):
下面是txt文件中的字符串(我想要的字符串从第四行开始):

从第4行开始,我想转换成dict。每个数字元组是dict中的一个键,另外两个是名为piece的类的实例(对象)的属性,“blanc”或“noir”是属性piece的值。“color”和“pion”是属性piece的值。类型(其他可能的值是“dame”)。 基本上,如果我想像上面那样手动填写dict,它是这样的:

self.cases = {}
self.cases[(3, 0)] = Piece("blanc", "pion")
self.cases[(5, 4)] = Piece("blanc", "pion")
self.cases[(2, 1)] = Piece("noir", "pion")
...
import re

f = open('data','r')
data = f.read()
f.close()

text = data.split('\n')
dict = {}
for line in text:
    key = re.findall(r"\((\(\d\,\s\d\)),", line)
    attr1 = re.findall(r",\s'(\w+)',", line)
    attr2 = re.findall(r",\s'(\w+)'\)", line)
    if len(key)>0:
        dict[key[0]] = (attr1[0], attr2[0])
print dict
我正在制作的函数使用字符串作为参数来填充dict。此函数用于另一个函数,该函数将读取如上所述的txt文件,并在文件中找到字符串,将其用作此函数的参数。因此,我还想知道如何在上面的txt文件中找到字符串,以便将其传递给此函数。最后一部分将在另一个函数中。可能有一个更简单的方法来做这件事,但我真的需要这样做,使一切都配合在一起


编辑:是的,这是真正的结构/格式,不幸的是我不能更改它。

如果这是真正的格式,最简单的方法是

rows = [x for x in open('file.ext', 'r')][3:]

for x in rows:
   key, color, thetype = eval(x)
   dict[key] = Piece(color, thetype)

若这真的是一种格式,那个么最简单的方法就是

rows = [x for x in open('file.ext', 'r')][3:]

for x in rows:
   key, color, thetype = eval(x)
   dict[key] = Piece(color, thetype)

若这真的是一种格式,那个么最简单的方法就是

rows = [x for x in open('file.ext', 'r')][3:]

for x in rows:
   key, color, thetype = eval(x)
   dict[key] = Piece(color, thetype)

若这真的是一种格式,那个么最简单的方法就是

rows = [x for x in open('file.ext', 'r')][3:]

for x in rows:
   key, color, thetype = eval(x)
   dict[key] = Piece(color, thetype)

如果该文件是由Python生成的,并且您可以访问用于生成它的程序,或者可以诱导具有访问权限的人,则应该考虑使用<代码>泡菜< /代码>模块来存储和保存Python数据的表示。 如果无法使用更可靠的存储机制,并且数据与示例中的数据完全相同,则可以对每一行执行以下操作:

 line = line.translate(None, '()')
 terms = line.split(',')
 self.cases[(terms[0], terms[1]) = Piece(terms[2], terms[3])

如果该文件是由Python生成的,并且您可以访问用于生成它的程序,或者可以诱导具有访问权限的人,则应该考虑使用<代码>泡菜< /代码>模块来存储和保存Python数据的表示。 如果无法使用更可靠的存储机制,并且数据与示例中的数据完全相同,则可以对每一行执行以下操作:

 line = line.translate(None, '()')
 terms = line.split(',')
 self.cases[(terms[0], terms[1]) = Piece(terms[2], terms[3])

如果该文件是由Python生成的,并且您可以访问用于生成它的程序,或者可以诱导具有访问权限的人,则应该考虑使用<代码>泡菜< /代码>模块来存储和保存Python数据的表示。 如果无法使用更可靠的存储机制,并且数据与示例中的数据完全相同,则可以对每一行执行以下操作:

 line = line.translate(None, '()')
 terms = line.split(',')
 self.cases[(terms[0], terms[1]) = Piece(terms[2], terms[3])

如果该文件是由Python生成的,并且您可以访问用于生成它的程序,或者可以诱导具有访问权限的人,则应该考虑使用<代码>泡菜< /代码>模块来存储和保存Python数据的表示。 如果无法使用更可靠的存储机制,并且数据与示例中的数据完全相同,则可以对每一行执行以下操作:

 line = line.translate(None, '()')
 terms = line.split(',')
 self.cases[(terms[0], terms[1]) = Piece(terms[2], terms[3])
如果输入是安全的(它来自受信任的一方),那么可以使用eval,它使用Python代码获取字符串,对其求值,然后返回结果

例如:

from __future__ import print_function
from collections import namedtuple
from pprint import pprint
import sys

# Read the entire file to a list of lines
with open('my_text.txt', 'r') as f:
    lines = f.readlines()

# Declare a Piece class, which is a named tuple (immutable)
Piece = namedtuple('Piece', ['color', 'piece'])

# The cases dictionary where we will write
cases = {}

# For lines 4 to last, counting them starting at 4...
for num_line, line in enumerate(lines[3:], start=4):
    try:
        # Evaluate the line (will return a tuple)
        a_tuple = eval(line)

        # Separate the first element from the rest
        key, params = a_tuple[0], a_tuple[1:]

        # Write in the dictionary. *params is substituted with an argument for
        # each element in the tuple params.
        cases[key] = Piece(*params)
    except:
        # If something was wrong, print the line that failed in the text file
        # and raise the exception to get the traceback and stop the program.
        print("Failed to parse line %d: %s" % (num_line, line), file=sys.stderr)
        raise

# Pretty print the result
pprint(cases)
如果输入是安全的(它来自受信任的一方),那么可以使用eval,它使用Python代码获取字符串,对其求值,然后返回结果

例如:

from __future__ import print_function
from collections import namedtuple
from pprint import pprint
import sys

# Read the entire file to a list of lines
with open('my_text.txt', 'r') as f:
    lines = f.readlines()

# Declare a Piece class, which is a named tuple (immutable)
Piece = namedtuple('Piece', ['color', 'piece'])

# The cases dictionary where we will write
cases = {}

# For lines 4 to last, counting them starting at 4...
for num_line, line in enumerate(lines[3:], start=4):
    try:
        # Evaluate the line (will return a tuple)
        a_tuple = eval(line)

        # Separate the first element from the rest
        key, params = a_tuple[0], a_tuple[1:]

        # Write in the dictionary. *params is substituted with an argument for
        # each element in the tuple params.
        cases[key] = Piece(*params)
    except:
        # If something was wrong, print the line that failed in the text file
        # and raise the exception to get the traceback and stop the program.
        print("Failed to parse line %d: %s" % (num_line, line), file=sys.stderr)
        raise

# Pretty print the result
pprint(cases)
如果输入是安全的(它来自受信任的一方),那么可以使用eval,它使用Python代码获取字符串,对其求值,然后返回结果

例如:

from __future__ import print_function
from collections import namedtuple
from pprint import pprint
import sys

# Read the entire file to a list of lines
with open('my_text.txt', 'r') as f:
    lines = f.readlines()

# Declare a Piece class, which is a named tuple (immutable)
Piece = namedtuple('Piece', ['color', 'piece'])

# The cases dictionary where we will write
cases = {}

# For lines 4 to last, counting them starting at 4...
for num_line, line in enumerate(lines[3:], start=4):
    try:
        # Evaluate the line (will return a tuple)
        a_tuple = eval(line)

        # Separate the first element from the rest
        key, params = a_tuple[0], a_tuple[1:]

        # Write in the dictionary. *params is substituted with an argument for
        # each element in the tuple params.
        cases[key] = Piece(*params)
    except:
        # If something was wrong, print the line that failed in the text file
        # and raise the exception to get the traceback and stop the program.
        print("Failed to parse line %d: %s" % (num_line, line), file=sys.stderr)
        raise

# Pretty print the result
pprint(cases)
如果输入是安全的(它来自受信任的一方),那么可以使用eval,它使用Python代码获取字符串,对其求值,然后返回结果

例如:

from __future__ import print_function
from collections import namedtuple
from pprint import pprint
import sys

# Read the entire file to a list of lines
with open('my_text.txt', 'r') as f:
    lines = f.readlines()

# Declare a Piece class, which is a named tuple (immutable)
Piece = namedtuple('Piece', ['color', 'piece'])

# The cases dictionary where we will write
cases = {}

# For lines 4 to last, counting them starting at 4...
for num_line, line in enumerate(lines[3:], start=4):
    try:
        # Evaluate the line (will return a tuple)
        a_tuple = eval(line)

        # Separate the first element from the rest
        key, params = a_tuple[0], a_tuple[1:]

        # Write in the dictionary. *params is substituted with an argument for
        # each element in the tuple params.
        cases[key] = Piece(*params)
    except:
        # If something was wrong, print the line that failed in the text file
        # and raise the exception to get the traceback and stop the program.
        print("Failed to parse line %d: %s" % (num_line, line), file=sys.stderr)
        raise

# Pretty print the result
pprint(cases)

纯Python字符串解决方案:

txt="""\
noir
False
None
((3, 0), 'blanc', 'pion')
((5, 4), 'blanc', 'pion')
((2, 1), 'noir', 'pion')
((2, 5), 'noir', 'pion')
((7, 2), 'blanc', 'pion')
((1, 2), 'noir', 'pion')
((6, 7), 'blanc', 'pion')
((7, 6), 'blanc', 'pion')
((6, 3), 'blanc', 'pion')
((5, 6), 'blanc', 'pion')
((5, 0), 'noir', 'pion')
((0, 1), 'noir', 'pion')
((3, 2), 'blanc', 'pion')
((2, 3), 'noir', 'pion')
((0, 7), 'noir', 'pion')
((1, 0), 'noir', 'pion')
((6, 5), 'blanc', 'pion')
((2, 7), 'noir', 'pion')
((7, 0), 'blanc', 'pion')
((6, 1), 'blanc', 'pion')
((7, 4), 'blanc', 'pion')
((0, 5), 'noir', 'pion')
((3, 4), 'noir', 'pion')"""

d={}
for line in txt.splitlines()[3:]:
    data=line.strip()[1:-1].split(',')
    d[line.partition(')')[0][1:]+')']=''.join(data[2:])
或者您可以从ast使用:

from ast import literal_eval

d={}
for line in txt.splitlines()[3:]:
    data=literal_eval(line)
    d[data[0]]=data[1:]
在任何一种情况下:

>>> d   
{(3, 0): ('blanc', 'pion'), (3, 2): ('blanc', 'pion'), (2, 1): ('noir', 'pion'), (2, 5): ('noir', 'pion'), (7, 2): ('blanc', 'pion'), (1, 2): ('noir', 'pion'), (6, 7): ('blanc', 'pion'), (7, 6): ('blanc', 'pion'), (6, 3): ('blanc', 'pion'), (5, 6): ('blanc', 'pion'), (5, 0): ('noir', 'pion'), (2, 7): ('noir', 'pion'), (5, 4): ('blanc', 'pion'), (2, 3): ('noir', 'pion'), (0, 7): ('noir', 'pion'), (1, 0): ('noir', 'pion'), (6, 5): ('blanc', 'pion'), (0, 1): ('noir', 'pion'), (7, 0): ('blanc', 'pion'), (6, 1): ('blanc', 'pion'), (7, 4): ('blanc', 'pion'), (0, 5): ('noir', 'pion'), (3, 4): ('noir', 'pion')}'blanc' 'pion'", '(1, 0)': " 'noir' 'pion'", '(1, 2)': " 'noir' 'pion'", '(6, 1)': " 'blanc' 'pion'", '(7, 0)': " 'blanc' 'pion'", '(2, 5)': " 'noir' 'pion'", '(5, 6)': " 'blanc' 'pion'", '(7, 6)': " 'blanc' 'pion'", '(5, 0)': " 'noir' 'pion'", '(7, 4)': " 'blanc' 'pion'", '(7, 2)': " 'blanc' 'pion'"}

纯Python字符串解决方案:

txt="""\
noir
False
None
((3, 0), 'blanc', 'pion')
((5, 4), 'blanc', 'pion')
((2, 1), 'noir', 'pion')
((2, 5), 'noir', 'pion')
((7, 2), 'blanc', 'pion')
((1, 2), 'noir', 'pion')
((6, 7), 'blanc', 'pion')
((7, 6), 'blanc', 'pion')
((6, 3), 'blanc', 'pion')
((5, 6), 'blanc', 'pion')
((5, 0), 'noir', 'pion')
((0, 1), 'noir', 'pion')
((3, 2), 'blanc', 'pion')
((2, 3), 'noir', 'pion')
((0, 7), 'noir', 'pion')
((1, 0), 'noir', 'pion')
((6, 5), 'blanc', 'pion')
((2, 7), 'noir', 'pion')
((7, 0), 'blanc', 'pion')
((6, 1), 'blanc', 'pion')
((7, 4), 'blanc', 'pion')
((0, 5), 'noir', 'pion')
((3, 4), 'noir', 'pion')"""

d={}
for line in txt.splitlines()[3:]:
    data=line.strip()[1:-1].split(',')
    d[line.partition(')')[0][1:]+')']=''.join(data[2:])
或者您可以从ast使用:

from ast import literal_eval

d={}
for line in txt.splitlines()[3:]:
    data=literal_eval(line)
    d[data[0]]=data[1:]
在任何一种情况下:

>>> d   
{(3, 0): ('blanc', 'pion'), (3, 2): ('blanc', 'pion'), (2, 1): ('noir', 'pion'), (2, 5): ('noir', 'pion'), (7, 2): ('blanc', 'pion'), (1, 2): ('noir', 'pion'), (6, 7): ('blanc', 'pion'), (7, 6): ('blanc', 'pion'), (6, 3): ('blanc', 'pion'), (5, 6): ('blanc', 'pion'), (5, 0): ('noir', 'pion'), (2, 7): ('noir', 'pion'), (5, 4): ('blanc', 'pion'), (2, 3): ('noir', 'pion'), (0, 7): ('noir', 'pion'), (1, 0): ('noir', 'pion'), (6, 5): ('blanc', 'pion'), (0, 1): ('noir', 'pion'), (7, 0): ('blanc', 'pion'), (6, 1): ('blanc', 'pion'), (7, 4): ('blanc', 'pion'), (0, 5): ('noir', 'pion'), (3, 4): ('noir', 'pion')}'blanc' 'pion'", '(1, 0)': " 'noir' 'pion'", '(1, 2)': " 'noir' 'pion'", '(6, 1)': " 'blanc' 'pion'", '(7, 0)': " 'blanc' 'pion'", '(2, 5)': " 'noir' 'pion'", '(5, 6)': " 'blanc' 'pion'", '(7, 6)': " 'blanc' 'pion'", '(5, 0)': " 'noir' 'pion'", '(7, 4)': " 'blanc' 'pion'", '(7, 2)': " 'blanc' 'pion'"}

纯Python字符串解决方案:

txt="""\
noir
False
None
((3, 0), 'blanc', 'pion')
((5, 4), 'blanc', 'pion')
((2, 1), 'noir', 'pion')
((2, 5), 'noir', 'pion')
((7, 2), 'blanc', 'pion')
((1, 2), 'noir', 'pion')
((6, 7), 'blanc', 'pion')
((7, 6), 'blanc', 'pion')
((6, 3), 'blanc', 'pion')
((5, 6), 'blanc', 'pion')
((5, 0), 'noir', 'pion')
((0, 1), 'noir', 'pion')
((3, 2), 'blanc', 'pion')
((2, 3), 'noir', 'pion')
((0, 7), 'noir', 'pion')
((1, 0), 'noir', 'pion')
((6, 5), 'blanc', 'pion')
((2, 7), 'noir', 'pion')
((7, 0), 'blanc', 'pion')
((6, 1), 'blanc', 'pion')
((7, 4), 'blanc', 'pion')
((0, 5), 'noir', 'pion')
((3, 4), 'noir', 'pion')"""

d={}
for line in txt.splitlines()[3:]:
    data=line.strip()[1:-1].split(',')
    d[line.partition(')')[0][1:]+')']=''.join(data[2:])
或者您可以从ast使用:

from ast import literal_eval

d={}
for line in txt.splitlines()[3:]:
    data=literal_eval(line)
    d[data[0]]=data[1:]
在任何一种情况下:

>>> d   
{(3, 0): ('blanc', 'pion'), (3, 2): ('blanc', 'pion'), (2, 1): ('noir', 'pion'), (2, 5): ('noir', 'pion'), (7, 2): ('blanc', 'pion'), (1, 2): ('noir', 'pion'), (6, 7): ('blanc', 'pion'), (7, 6): ('blanc', 'pion'), (6, 3): ('blanc', 'pion'), (5, 6): ('blanc', 'pion'), (5, 0): ('noir', 'pion'), (2, 7): ('noir', 'pion'), (5, 4): ('blanc', 'pion'), (2, 3): ('noir', 'pion'), (0, 7): ('noir', 'pion'), (1, 0): ('noir', 'pion'), (6, 5): ('blanc', 'pion'), (0, 1): ('noir', 'pion'), (7, 0): ('blanc', 'pion'), (6, 1): ('blanc', 'pion'), (7, 4): ('blanc', 'pion'), (0, 5): ('noir', 'pion'), (3, 4): ('noir', 'pion')}'blanc' 'pion'", '(1, 0)': " 'noir' 'pion'", '(1, 2)': " 'noir' 'pion'", '(6, 1)': " 'blanc' 'pion'", '(7, 0)': " 'blanc' 'pion'", '(2, 5)': " 'noir' 'pion'", '(5, 6)': " 'blanc' 'pion'", '(7, 6)': " 'blanc' 'pion'", '(5, 0)': " 'noir' 'pion'", '(7, 4)': " 'blanc' 'pion'", '(7, 2)': " 'blanc' 'pion'"}

纯Python字符串解决方案:

txt="""\
noir
False
None
((3, 0), 'blanc', 'pion')
((5, 4), 'blanc', 'pion')
((2, 1), 'noir', 'pion')
((2, 5), 'noir', 'pion')
((7, 2), 'blanc', 'pion')
((1, 2), 'noir', 'pion')
((6, 7), 'blanc', 'pion')
((7, 6), 'blanc', 'pion')
((6, 3), 'blanc', 'pion')
((5, 6), 'blanc', 'pion')
((5, 0), 'noir', 'pion')
((0, 1), 'noir', 'pion')
((3, 2), 'blanc', 'pion')
((2, 3), 'noir', 'pion')
((0, 7), 'noir', 'pion')
((1, 0), 'noir', 'pion')
((6, 5), 'blanc', 'pion')
((2, 7), 'noir', 'pion')
((7, 0), 'blanc', 'pion')
((6, 1), 'blanc', 'pion')
((7, 4), 'blanc', 'pion')
((0, 5), 'noir', 'pion')
((3, 4), 'noir', 'pion')"""

d={}
for line in txt.splitlines()[3:]:
    data=line.strip()[1:-1].split(',')
    d[line.partition(')')[0][1:]+')']=''.join(data[2:])
或者您可以从ast使用:

from ast import literal_eval

d={}
for line in txt.splitlines()[3:]:
    data=literal_eval(line)
    d[data[0]]=data[1:]
在任何一种情况下:

>>> d   
{(3, 0): ('blanc', 'pion'), (3, 2): ('blanc', 'pion'), (2, 1): ('noir', 'pion'), (2, 5): ('noir', 'pion'), (7, 2): ('blanc', 'pion'), (1, 2): ('noir', 'pion'), (6, 7): ('blanc', 'pion'), (7, 6): ('blanc', 'pion'), (6, 3): ('blanc', 'pion'), (5, 6): ('blanc', 'pion'), (5, 0): ('noir', 'pion'), (2, 7): ('noir', 'pion'), (5, 4): ('blanc', 'pion'), (2, 3): ('noir', 'pion'), (0, 7): ('noir', 'pion'), (1, 0): ('noir', 'pion'), (6, 5): ('blanc', 'pion'), (0, 1): ('noir', 'pion'), (7, 0): ('blanc', 'pion'), (6, 1): ('blanc', 'pion'), (7, 4): ('blanc', 'pion'), (0, 5): ('noir', 'pion'), (3, 4): ('noir', 'pion')}'blanc' 'pion'", '(1, 0)': " 'noir' 'pion'", '(1, 2)': " 'noir' 'pion'", '(6, 1)': " 'blanc' 'pion'", '(7, 0)': " 'blanc' 'pion'", '(2, 5)': " 'noir' 'pion'", '(5, 6)': " 'blanc' 'pion'", '(7, 6)': " 'blanc' 'pion'", '(5, 0)': " 'noir' 'pion'", '(7, 4)': " 'blanc' 'pion'", '(7, 2)': " 'blanc' 'pion'"}

下面是一种使用正则表达式提取数据的简单方法,如下所示:

self.cases = {}
self.cases[(3, 0)] = Piece("blanc", "pion")
self.cases[(5, 4)] = Piece("blanc", "pion")
self.cases[(2, 1)] = Piece("noir", "pion")
...
import re

f = open('data','r')
data = f.read()
f.close()

text = data.split('\n')
dict = {}
for line in text:
    key = re.findall(r"\((\(\d\,\s\d\)),", line)
    attr1 = re.findall(r",\s'(\w+)',", line)
    attr2 = re.findall(r",\s'(\w+)'\)", line)
    if len(key)>0:
        dict[key[0]] = (attr1[0], attr2[0])
print dict
这将处理文件中行中数据的任何情况,并仅捕获所需的数据形式,并且您不必担心格式错误或空行,输出将是:

{'(3, 0)': ('blanc', 'pion'), '(3, 4)': ('noir', 'pion'), '(2, 7)': ('noir', 'pion'), '(2, 1)': ('noir', 'pion'), '(3, 2)': ('blanc', 'pion'), '(2, 3)': ('noir', 'pion'), '(0, 1)': ('noir', 'pion'), '(0, 7)': ('noir', 'pion'), '(0, 5)': ('noir', 'pion'), '(6, 3)': ('blanc', 'pion'), '(6, 5)': ('blanc', 'pion'), '(5, 4)': ('blanc', 'pion'), '(6, 7)': ('blanc', 'pion'), '(1, 0)': ('noir', 'pion'), '(1, 2)': ('noir', 'pion'), '(6, 1)': ('blanc', 'pion'), '(7, 0)': ('blanc', 'pion'), '(2, 5)': ('noir', 'pion'), '(5, 6)': ('blanc', 'pion'), '(7, 6)': ('blanc', 'pion'), '(5, 0)': ('noir', 'pion'), '(7, 4)': ('blanc', 'pion'), '(7, 2)': ('blanc', 'pion')}

希望这是一个帮助。

下面是一个使用正则表达式提取数据的简单方法,如下所示:

self.cases = {}
self.cases[(3, 0)] = Piece("blanc", "pion")
self.cases[(5, 4)] = Piece("blanc", "pion")
self.cases[(2, 1)] = Piece("noir", "pion")
...
import re

f = open('data','r')
data = f.read()
f.close()

text = data.split('\n')
dict = {}
for line in text:
    key = re.findall(r"\((\(\d\,\s\d\)),", line)
    attr1 = re.findall(r",\s'(\w+)',", line)
    attr2 = re.findall(r",\s'(\w+)'\)", line)
    if len(key)>0:
        dict[key[0]] = (attr1[0], attr2[0])
print dict
这将处理文件中行中数据的任何情况,并仅捕获所需的数据形式,并且您不必担心格式错误或空行,输出将是:

{'(3, 0)': ('blanc', 'pion'), '(3, 4)': ('noir', 'pion'), '(2, 7)': ('noir', 'pion'), '(2, 1)': ('noir', 'pion'), '(3, 2)': ('blanc', 'pion'), '(2, 3)': ('noir', 'pion'), '(0, 1)': ('noir', 'pion'), '(0, 7)': ('noir', 'pion'), '(0, 5)': ('noir', 'pion'), '(6, 3)': ('blanc', 'pion'), '(6, 5)': ('blanc', 'pion'), '(5, 4)': ('blanc', 'pion'), '(6, 7)': ('blanc', 'pion'), '(1, 0)': ('noir', 'pion'), '(1, 2)': ('noir', 'pion'), '(6, 1)': ('blanc', 'pion'), '(7, 0)': ('blanc', 'pion'), '(2, 5)': ('noir', 'pion'), '(5, 6)': ('blanc', 'pion'), '(7, 6)': ('blanc', 'pion'), '(5, 0)': ('noir', 'pion'), '(7, 4)': ('blanc', 'pion'), '(7, 2)': ('blanc', 'pion')}

希望这是一个帮助。

下面是一个使用正则表达式提取数据的简单方法,如下所示:

self.cases = {}
self.cases[(3, 0)] = Piece("blanc", "pion")
self.cases[(5, 4)] = Piece("blanc", "pion")
self.cases[(2, 1)] = Piece("noir", "pion")
...
import re

f = open('data','r')
data = f.read()
f.close()

text = data.split('\n')
dict = {}
for line in text:
    key = re.findall(r"\((\(\d\,\s\d\)),", line)
    attr1 = re.findall(r",\s'(\w+)',", line)
    attr2 = re.findall(r",\s'(\w+)'\)", line)
    if len(key)>0:
        dict[key[0]] = (attr1[0], attr2[0])
print dict
这将处理文件中行中数据的任何情况,并仅捕获所需的数据形式,并且您不必担心格式错误或空行,输出将是:

{'(3, 0)': ('blanc', 'pion'), '(3, 4)': ('noir', 'pion'), '(2, 7)': ('noir', 'pion'), '(2, 1)': ('noir', 'pion'), '(3, 2)': ('blanc', 'pion'), '(2, 3)': ('noir', 'pion'), '(0, 1)': ('noir', 'pion'), '(0, 7)': ('noir', 'pion'), '(0, 5)': ('noir', 'pion'), '(6, 3)': ('blanc', 'pion'), '(6, 5)': ('blanc', 'pion'), '(5, 4)': ('blanc', 'pion'), '(6, 7)': ('blanc', 'pion'), '(1, 0)': ('noir', 'pion'), '(1, 2)': ('noir', 'pion'), '(6, 1)': ('blanc', 'pion'), '(7, 0)': ('blanc', 'pion'), '(2, 5)': ('noir', 'pion'), '(5, 6)': ('blanc', 'pion'), '(7, 6)': ('blanc', 'pion'), '(5, 0)': ('noir', 'pion'), '(7, 4)': ('blanc', 'pion'), '(7, 2)': ('blanc', 'pion')}

希望这是一个帮助。

下面是一个使用正则表达式提取数据的简单方法,如下所示:

self.cases = {}
self.cases[(3, 0)] = Piece("blanc", "pion")
self.cases[(5, 4)] = Piece("blanc", "pion")
self.cases[(2, 1)] = Piece("noir", "pion")
...
import re

f = open('data','r')
data = f.read()
f.close()

text = data.split('\n')
dict = {}
for line in text:
    key = re.findall(r"\((\(\d\,\s\d\)),", line)
    attr1 = re.findall(r",\s'(\w+)',", line)
    attr2 = re.findall(r",\s'(\w+)'\)", line)
    if len(key)>0:
        dict[key[0]] = (attr1[0], attr2[0])
print dict
这将处理文件中行中数据的任何情况,并仅捕获所需的数据形式,并且您不必担心格式错误或空行,输出将是:

{'(3, 0)': ('blanc', 'pion'), '(3, 4)': ('noir', 'pion'), '(2, 7)': ('noir', 'pion'), '(2, 1)': ('noir', 'pion'), '(3, 2)': ('blanc', 'pion'), '(2, 3)': ('noir', 'pion'), '(0, 1)': ('noir', 'pion'), '(0, 7)': ('noir', 'pion'), '(0, 5)': ('noir', 'pion'), '(6, 3)': ('blanc', 'pion'), '(6, 5)': ('blanc', 'pion'), '(5, 4)': ('blanc', 'pion'), '(6, 7)': ('blanc', 'pion'), '(1, 0)': ('noir', 'pion'), '(1, 2)': ('noir', 'pion'), '(6, 1)': ('blanc', 'pion'), '(7, 0)': ('blanc', 'pion'), '(2, 5)': ('noir', 'pion'), '(5, 6)': ('blanc', 'pion'), '(7, 6)': ('blanc', 'pion'), '(5, 0)': ('noir', 'pion'), '(7, 4)': ('blanc', 'pion'), '(7, 2)': ('blanc', 'pion')}

希望这能有所帮助。

这种结构是从哪里来的?操作起来似乎并不简单这就是为什么我在另一个问题中问这些数据去了哪里。将python
repr
写入一个文件并不是将其重新写入的好方法。这真的是文件的结构,还是一个简化的示例?如果真的是str