如何从文本文件创建复杂的字典?

时间:2018-04-25 11:43:36

标签: python

我将文本文件称为 testText.txt ,如下所示:

Calendar calendar = Calendar.getInstance();
//optional step
calendar.setFirstDayOfWeek(Calendar.SUNDAY);
calendar.set(Calendar.DAY_OF_WEEK, Calendar.SATURDAY);
int lastDateOfWeek = calendar.get(Calendar.DATE);

我希望将文本文件转换为如下所示的字典:

#Rooms
room Hall
room Kitchen
room Storage
room Bedroom
room Bathroom
room Garage
#Doors
door N open Hall Bedroom
door N closed Storage Kitchen
door E locked Hall Storage
door E open Bedroom Kitchen
door N open Bedroom Bathroom
door S open Bedroom Hall
door S open Bathroom Bedroom
door W locked Hall Garage
door W open Kitchen Bedroom
door S closed Kitchen Storage
door W open Storage Hall
door E locked Garage Hall
#Items
item car Garage STATIONARY
item remote Kitchen MOVE
item key Bedroom USE
item key Hall USE
#Start position
start Hall

我已经尝试了代码,但这种转换对我来说似乎很复杂。我尝试过了: ROOMS

的词典
tempRooms={1:{"name":"Hall","N":{"dir":2,"status":"open"},"E":{"dir":3,"status":"locked"},"W":{"dir":4,"status":"locked"},"item":{"itemName":"key","movementStatus":"USE"},"start":1},
       2:{"name":"Bedroom","E":{"dir":5,"status":"open"},"N":{"dir":6,"status":"open"},"S":{"dir":1,"status":"open"},"item":{"itemName":"key","movementStatus":"USE"},"start":1},
       3:{"name":"Storage","N":{"dir":5,"status":"closed"},"W":{"dir":1,"status":"open"},"start":1},
       4:{"name":"Garage","E":{"dir":1,"status":"locked"},"item":{"itemName":"car","movementStatus":"STATIONARY"},"start":1},
       5:{"name":"Kitchen","W":{"dir":2,"status":"open"},"S":{"dir":3,"status":"closed"},"item":{"itemName":"remote","movementStatus":"MOVE"},"start":1},
       6:{"name":"Bathroom","S":{"dir":2,"status":"open"},"start":1}}

DOORS

的字典
with open(filename,'r') as input_data:
    for line in input_data:
        if line.strip() == '#Rooms':  # Or whatever test is needed
            break
    for line in input_data:  # This keeps reading the file
        if line.strip() == '#Doors':
            break
        lines=line.strip().split()
        a=lines[0]
        b=lines[1]
        rooms[a]=b
        print(rooms['room'])

但我无法获得所需的输出。我尝试了不同的时间和不同的类型,但每次都失败。我必须开发一个互动小说游戏(基于文本的冒险游戏)。所以,我的文本文件中有数据,我想要字典的确切输出。 Start Hall是起始位置,Items表示项目存在的位置,然后用户可以拿起或使用它。 高于1,2,3 ......等。表示键。 请帮助我获得所需的输出。

1 个答案:

答案 0 :(得分:1)

您希望避免不必要的处理。循环每一行。忽略以#开头的行(它们没有任何意义)。将每一行拆分为单词。看第一个字。如果第一个单词是空格,请将其添加到词典中。如果它是门或项目,请将其添加到字典中的相应房间。