从文本文件+Python创建Dict:TypeError:“str”对象不支持项分配

2024-05-16 05:58:36 发布

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

正在尝试从此段文本创建dict:

game_name: Adventure 1
game_goal: Find the magic helmet and bring it to Hans.
game_goalloc: 8
game_goalobj: helmet
game_start: 4
game_xsize: 3
game_ysize: 3

以“config.txt”的形式读入,不断收到类型错误:“str”对象不支持项分配

难道我一辈子都不明白为什么在我的代码的其他地方做同样的操作。。。地狱

with open('config.txt') as f:
    lines = f.readlines()

for line in lines:
    line = line.strip()
    if "game_" in line:
        game = line.split('_')[-1]
        k = game.split(':')[0]
        v = game.split(':')[-1]
        print(k)
        print(v)
        game[k] = {}
        game[k] = v


Tags: namein文本txtgameconfiglinefind
3条回答
lines = """
game_name: Adventure 1
game_goal: Find the magic helmet and bring it to Hans.
game_goalloc: 8
game_goalobj: helmet
game_start: 4
game_xsize: 3
game_ysize: 3
""".strip().splitlines()

game_dict = {}

for line in lines:
    line = line.strip()
    if "game_" in line:
        game = line.split('_')[-1]
        k = game.split(':')[0].strip()
        v = game.split(':')[-1].strip()
        print(k)
        print(v)
        game_dict[k] = {}
        game_dict[k] = v

print(game_dict)

也许这就是你想要的

创建了一个空字典game_dict = {}并对其进行了更新

 with open('game1.txt') as f:
        lines = f.readlines()
    game_dict = {}
    for line in lines:
        line = line.strip()
    
        if "game_" in line:
            game = line.split('_')[-1]
    
            k = game.split(':')[0]
            game_dict[k] = ""
            v = game.split(':')[-1]
            game_dict[k] = v
    
    
    print(game_dict)

输出

{'name': ' Adventure 1', 'goal': ' Find the magic helmet and bring it to Hans.', 'goalloc': ' 8', 'goalobj': ' helmet', 'start': ' 4', 'xsize': ' 3', 'ysize': ' 3'}
    game = line.split('_')[-1]
    k = game.split(':')[0]
    v = game.split(':')[-1]
    print(k)
    print(v)
    game[k] = {}
    game[k] = v

在最后两行代码中,您试图将“game”赋值为空{},然后是v。这将导致错误

相关问题 更多 >