从python中的文件制作字典

时间:2014-11-07 22:27:52

标签: python file dictionary

我正在尝试制作一个以演员姓名为键的词典,以及他们所在的电影作为值

该文件如下所示:

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

3 个答案:

答案 0 :(得分:1)

您需要开始使用超级有用的ipdb模块。

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

如果你习惯了这个过程,它将在这个以及将来的调试中为你提供很多帮助。

答案 1 :(得分:0)

试试这个:

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:]是他所有的电影名称


您使用readline readline只读取line.suppose下面是一个名为test.txt的文件

Hello stackoverflow
hello Hackaholic

代码:

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

输出:

Hello stackoverflow
hello Hackaholic

你还需要将你的readline放在一边循环,你还需要做一些其他的改变。

答案 2 :(得分:0)

>>> 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']}