从python文件生成字典

2024-06-17 12:48:25 发布

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

我正在努力制作一本字典,以演员的名字为关键字,以他们在其中的电影为价值

文件如下所示:

Brad Pitt,Sleepers,Troy,Meet Joe Black,Oceans Eleven,Seven,Mr & Mrs Smith
Tom Hanks,You have got mail,Apollo 13,Sleepless in Seattle,Catch Me If You Can

我想把这个作为输出:

{Brad Pitt : Sleepers,Troy,Meet Joe Black,Oceans Eleven,Seven,Mr & Mrs Smith
Tom Hanks : You have got mail,Apollo 13,Sleepless in Seattle,Catch Me If You Can}

我认为我的问题是由于某种原因无法访问该文件,尽管我的代码中肯定有其他一些我看不到的问题。以下是我所拥有的:

from Myro import *
    def makeDictionaryFromFile():
    dictionary1={}
    try:
        infile = open("films.txt","r")
        nextLineFromFile = infile.readline().rstrip('\r\n')
        while (nextLineFromFile != ""):
            line = nextLineFromFile.split(",")
            first=line[0]
            dictionary1[first]=line[1:]
            nextLineFromFile = infile.readline().rstrip('\r\n')
    except:
        print ("File not found! (or other error!)")
    return dictionary1

Tags: 文件youlineinfileblackjoepittmeet
3条回答
>>> dictionary1 = {}
>>> for curr_line in open("films.txt").xreadlines():
...     split_line = curr_line.strip().split(",")
...     dictionary1[split_line.pop(0)] = split_line

>>> dictionary1
{'Brad Pitt': ['Sleepers', 'Troy', 'Meet Joe Black', 'Oceans Eleven', 'Seven', 'Mr & Mrs Smith'], 'Tom Hanks': ['You have got mail', 'Apollo 13', 'Sleepless in Seattle', 'Catch Me If You Can']}

试试这个:

mydict = {}
f = open('file','r')
for x in f:
    s = s.strip('\r\n').split(',')
    mydict[s[0]] = ",".join(s[1:])
print mydict

s[0]将有演员的名字,s[1:]是他所有电影的名字


使用readlinereadline只能读取行。假设下面是一个名为test.txt的文件

Hello stackoverflow
hello Hackaholic

代码:

f=open('test.txt')
print f.readline()
print f.readline()

输出:

Hello stackoverflow
hello Hackaholic

您还需要将readline放在side while循环中,还需要做一些其他更改。你知道吗

您需要开始使用超级有用的ipdb模块。你知道吗

try:
  # some error
except Exception as e:
  print e
  import ipdb
  ipdb.set_trace()

如果您习惯了这个过程,它将在这方面以及将来的调试中对您有很大帮助。你知道吗

相关问题 更多 >