从fi创建元组dict

2024-09-22 16:43:27 发布

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

我有一个文件是这样的:

利默里克

8安培

5个B

昆坦语(英语)

0安培

0个B

我想把它做成这样一个字典:

{'Limerick':([8,5],'A','B']),'Quintain(英语)':([0,0],'A','B'])}

到目前为止,我已经能够得到:

{Limerick':[],'Rondeau':[],'Haiku':[],'Quintain(英语)':[],'Sonnet':[]}

但是在那之后我不知道如何附加8a,5b等等。我试着得到它们开始和停止的索引,但是看起来Python的IO不允许这样做。你知道吗

假设,我试着把8a,5b加到一个列表中,然后把8,5和A,B加到两个列表中,然后把它们分类。但这似乎不可能/非常无效。你知道吗

我的尝试(诗歌形式是我设法得到的):

def read_poetry_form_descriptions(poetry_forms_file):

    poem_file = open(poetry_forms_file, 'r')
    temp_poem, poem_form = {}, {}

    for line in poem_file:
        temp_poem[line.strip()] = ()
        poem_form.pop('', None)

    poem_file.close()

    for key in temp_poem:
        if key[0:3].isalpha():
            poem_form[key] = []

    print(poem_form)

Tags: 文件keyinform列表forpoetry字典
1条回答
网友
1楼 · 发布于 2024-09-22 16:43:27

这是你的问题的一个可能的解决办法。你知道吗

def read_poetry_from_desc(poetry_forms_file):
    poem_form = {}

    with open(poetry_forms_file, 'r') as f:
        cur_header = None # latest header found in file

        for line in f:
            line = line.strip()

            # Skip empty lines
            if len(line) == 0:
                continue

            if line[0].isalpha():
                # Found new header, add empty entry to dict
                cur_header = line
                poem_form[cur_header] = ([], [])

            else:
                # Found data, record it
                pair = line.split() # split on space

                data = poem_form[cur_header]                
                data[0].append(int(pair[0]))
                data[1].append(pair[1])

    return poem_form

编辑:
这样做的目的是在你知道信息的情况下填充字典。您知道文件的布局是一个标签,在找到另一个标签之前,后面的数据属于该标签。你知道吗

这也可以提高效率,因为数据可以采用的形式非常有限。它要么是由字母字符组成的标签,要么是以数字开头的数据。因此,我们可以通过看行是否以字母开头来区分两者。你知道吗

因为字典中每个键的值poem_form的格式是([], []),所以当我们在文件中看到一个新标签时,它会与空列表一起添加到字典中。我们还记录了当前正在为特定标签(cur_header)进行累积。你知道吗

每当我们看到数据时,它就会被分解并累积在当前标签的任何位置(cur_label)。你知道吗

有关with的解释,请参见link。它比我解释得更好。从本质上讲,with是在您有一个文本块时使用的,这个文本块在使用的开始和结束时都有一个操作。这里我用它来表示open。通常,您必须打开文件,然后在完成后关闭它。在这个函数中,当退出with作用域时,文件将自动关闭。要了解为什么会发生这种情况,请参阅链接文章。你知道吗

相关问题 更多 >