python用字符串填充字典

2024-05-08 06:34:59 发布

您现在位置:Python中文网/ 问答频道 /正文

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

def load_a_string(self, thestring):

下面是txt文件中字符串的格式(我想要的字符串从第四行开始):

^{pr2}$

从第四行开始,我想转换成dict。每个数元组都是dict中的一个键,另外两个是一个名为piece的类的实例(对象)的属性,“blanc”或“noir”是该属性的值单件颜色“pion”是属性的值件。类型(另一个可能的值是“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")
...

我所做的函数以一个字符串作为参数来填充dict。这个函数将用于另一个函数,该函数将读取上面的txt文件,并在文件中找到该字符串,将其用作该函数的参数。所以我还想知道如何在像上面这样的txt文件中找到字符串,这样我就可以把它传递给这个函数。最后一部分将在另一个函数中。可能有一个更简单的方法来做到这一点,但我真的需要这样做,这样一切都能配合起来。在

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


Tags: 文件对象函数字符串selftxt参数piece
3条回答

如果该文件是由Python生成的,并且您可以访问用于生成它的程序,或者可以诱导具有访问权限的人,那么您应该考虑使用pickle模块来存储和保存Python数据的表示。在

如果不能使用更可靠的存储机制,并且数据与示例中的数据完全相同,则可以对每行执行以下操作:

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

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

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

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

如果输入是安全的(它来自受信任方),则可以使用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)

相关问题 更多 >