我正试着制作一本字典,把演员的名字作为钥匙,把他们的电影作为价值
该文件如下所示:
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发布于 2014-11-07 22:38:15
您需要开始使用超级有用的ipdb模块。
try:
# some error
except Exception as e:
print e
import ipdb
ipdb.set_trace()如果您习惯了这个过程,它将对您在这方面以及将来的调试中有很大的帮助。
发布于 2014-11-07 22:37:54
试试这个:
mydict = {}
f = open('file','r')
for x in f:
s = s.strip('\r\n').split(',')
mydict[s[0]] = ",".join(s[1:])
print mydicts[0]将有演员的名字,s[1:]是他所有的电影名字
使用readline读行只读取下面的line.suppose是一个名为test.txt的文件
Hello stackoverflow
hello Hackaholic代码:
f=open('test.txt')
print f.readline()
print f.readline()产出:
Hello stackoverflow
hello Hackaholic您还需要将您的readline放在侧while循环中,还需要进行其他一些更改。
发布于 2014-11-07 22:38:51
>>> 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']}https://stackoverflow.com/questions/26811153
复制相似问题