我目前遇到了一个我无法正确思考的问题
我有一个以特定格式读取的文本文件的情况
(捕食者)吃(猎物)
我正在尝试做的是将它放入字典中,但是在某些情况下存在多行。
(捕食者)吃(猎物)
同一个捕食者出现吃不同的猎物。
到目前为止,这就是它的样子......
import sys
predpraydic={}#Establish universial dictionary for predator and prey
openFile = open(sys.argv[1], "rt") # open the file
data = openFile.read() # read the file
data = data.rstrip('\n') #removes the empty line ahead of the last line of the file
predpraylist = data.split('\n') #splits the read file into a list by the new line character
for items in range (0, len(predpraylist)): #loop for every item in the list in attempt to split the values and give a list of lists that contains 2 values for every list, predator and prey
predpraylist[items]=predpraylist[items].split("eats") #split "eats" to retrive the two values
for predpray in range (0, 2): #loop for the 2 values in the list
predpraylist[items][predpray]=predpraylist[items][predpray].strip() #removes the empty space caued by splitting the two values
for items in range (0, len(predpraylist)
if
for items in range (0, len(predpraylist)): # Loop in attempt to place these the listed items into a dictionary with a key of the predator to a list of prey
predpraydic[predpraylist[items][0]] = predpraylist[items][1]
print(predpraydic)
openFile.close()
如您所见,我只是将格式转储到我尝试转换为字典的列表中。
但是这种方法只接受一个键值。我想要有两件事的东西
狮子吃斑马 狮子吃狗
有一本字典
狮子:['斑马','狗']
我想不出这样做的方法。任何帮助,将不胜感激。