Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/363.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python-从txt文件创建dict_Python - Fatal编程技术网

Python-从txt文件创建dict

Python-从txt文件创建dict,python,Python,我们收到一个文件(.txt),格式如下: Johnson, Joana Volleyball Club Erickson, John Mcdonald, Joe Smith, Johnny Debate Club Chess Club McIlroy, Molly Dino, Dennis Jackson, Jamie Gibson, Ginny Fried, John 我必须编写一个函数来调用这个文件,并以以下形式返回一个字典:{'first person's name':[list o

我们收到一个文件(.txt),格式如下:

Johnson, Joana
Volleyball Club
Erickson, John
Mcdonald, Joe

Smith, Johnny
Debate Club
Chess Club
McIlroy, Molly
Dino, Dennis

Jackson, Jamie
Gibson, Ginny
Fried, John
我必须编写一个函数来调用这个文件,并以以下形式返回一个字典:{'first person's name':[list of friends in Earth stanza]因此应该返回:

{'Johnson,Joana':['Erickson,John','Mcdonald,Joe','Smith,Johnny':['McIlroy,Molly','Dino,Dennis','Jackson,Jamie':['Gibson,Ginny','Fried,John']}

我在下面编写了一个函数,但它只处理文件的第一节,而不是全部,因此返回:

{'Johnson,Joana':['Erickson,John','Mcdonald,Joe']}

我只是python的初学者,所以如果有人能帮助我而不使它复杂化,我将非常感激,我似乎无法处理整个文件

def name_to_friends(file):

    '''(file open for reading) -> dict of {str: list of str}
    '''

    for line in file:
        dic = {}
        lst = []
        for line in file:
            if line == '\n':
                dic.update({lst[0]:lst[1:]})
                break
            else:
                name = line.strip()        
                if ',' in line:
                    lst.append(line)
    return dic

您就快到了;删除
分隔符
;并在每次向词典中添加其他姓名和朋友时清除列表对象:

def name_to_friends(file):
    for line in file:
        dic = {}
        lst = []
        for line in file:
            if line == '\n':
                dic.update({lst[0]:lst[1:]})
                lst = []
            else:
                name = line.strip()        
                if ',' in line:
                    lst.append(line)

        if lst:
            dic.update({lst[0]:lst[1:]})

    return dic
当文件末尾没有空行时,需要最后一个
(如果需要lst

当您第一次遇到空行时,
break
语句将完全停止读取文件;通过删除它,您可以继续到下一个块

更惯用的方法是:

def name_to_friends(file):
    dic = {}

    for line in file:
        line = line.strip()
        # skip empty lines until we find the start of a block
        if not line:
            continue

        friends = dic[line] = []
        for line in file:
            line = line.strip()
            if not line:
                break  # end of block, continue to the next list of friends
            if ',' in line:
                friends.append(line)

    return dic

这会在第一个循环中的文件行上嵌套第二个循环;这也会提高文件行读取位置,因此当内部循环停止时(因为文件已完成或我们只是读取一个空行),外部循环将继续读取我们结束时的内容。

您就快到了;删除
中断
;并在每次向词典中添加其他姓名和朋友时清除列表对象:

def name_to_friends(file):
    for line in file:
        dic = {}
        lst = []
        for line in file:
            if line == '\n':
                dic.update({lst[0]:lst[1:]})
                lst = []
            else:
                name = line.strip()        
                if ',' in line:
                    lst.append(line)

        if lst:
            dic.update({lst[0]:lst[1:]})

    return dic
当文件末尾没有空行时,需要最后一个
(如果需要lst

当您第一次遇到空行时,
break
语句将完全停止读取文件;通过删除它,您可以继续到下一个块

更惯用的方法是:

def name_to_friends(file):
    dic = {}

    for line in file:
        line = line.strip()
        # skip empty lines until we find the start of a block
        if not line:
            continue

        friends = dic[line] = []
        for line in file:
            line = line.strip()
            if not line:
                break  # end of block, continue to the next list of friends
            if ',' in line:
                friends.append(line)

    return dic

这会在第一个循环中的文件行上嵌套第二个循环;这也会提高文件行读取位置,因此当内部循环停止时(因为文件已完成或我们只是读取了一个空行),外部循环将继续读取我们停止的位置。

如果文件不是太大,您可以执行以下操作

{k[0]: k[1:] for k in [l.split('\n') for l in file.read().split('\n\n')]}
编辑:要删除梅花(无逗号),您可以

{k[0]: [fr for fr in k[1:] if ',' in fr] for k in [ln.split('\n') for ln in file.read().split('\n\n')]}

如果文件不是太大,您可以简单地执行以下操作

{k[0]: k[1:] for k in [l.split('\n') for l in file.read().split('\n\n')]}
编辑:要删除梅花(无逗号),您可以

{k[0]: [fr for fr in k[1:] if ',' in fr] for k in [ln.split('\n') for ln in file.read().split('\n\n')]}

他们刚刚启动Python,您将对它们进行一行列表理解…您需要跳过不带逗号的行。我认为您需要修改列表理解部分-
[line for l in file.read().split('\n\n')for line in l.split('\n')if','in line]
@RobWatts然后我失去了Friendsmo的分组,大而复杂的一行程序真的伤害了python社区。难怪pylint抱怨超过80个字符的行。他们刚刚开始使用python,你要对它们进行一行列表理解……你需要跳过没有逗号的行。我认为你需要这样做修改列表理解部分-
[line for l in file.read().split('\n\n')for line in l.split('\n')if','in line]
@RobWatts然后我失去了对Friendsmo的分组,大而复杂的单行程序确实伤害了python社区。难怪pylint抱怨行超过80个字符。