Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/311.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python将新数据迭代到嵌套字典中_Python_Python 3.x - Fatal编程技术网

Python将新数据迭代到嵌套字典中

Python将新数据迭代到嵌套字典中,python,python-3.x,Python,Python 3.x,我一直在开发一个Python角色扮演游戏,我有一个从文本文件导入项目数据的函数。文本文件的结构如下所示: WEAPON 3 sword_of_eventual_obsolescence 6 10 2 0 10 WEAPON 4 dagger_of_bluntness 2 5 3 1 0 WEAPON 5 sword_of_extreme_flimsiness 3 8 3 7 0 数据导入过程如下所示: def items_get(): import os global item

我一直在开发一个Python角色扮演游戏,我有一个从文本文件导入项目数据的函数。文本文件的结构如下所示:

WEAPON 3 sword_of_eventual_obsolescence 6 10 2 0 10
WEAPON 4 dagger_of_bluntness 2 5 3 1 0
WEAPON 5 sword_of_extreme_flimsiness 3 8 3 7 0
数据导入过程如下所示:

def items_get():
    import os
    global items
    items = {
        "weapon":{},
        "armour":{},
        "potion":{},
        "misc":{}
    }
    file_dir = ( os.getcwd() + '\Code\items.txt' )

    file_in = open( file_dir, 'r')
    for each_line in file_in:
        line = file_in.readline()
        line = line.split(' ')
        if line[0] == "WEAPON":
            weapon_id = line[1]
            name = line[2]
            attack_min = line[3]
            attack_max = line[4]
            range = line[5]
            weight = line[6]
            value = line[7]
            weapon_data = {
                "name": name.replace('_', ' '),
                "atk_min": attack_min,
                "atk_max": attack_max,
                "rng": range,
                "wt": weight,
                "val": value,
            }
            items["weapon"][weapon_id] = {}
            items["weapon"][weapon_id].update(weapon_data)
但是,当我打印物品[“武器”]时,我得到以下信息:

{'4': {'wt': '1', 'atk_min': '2', 'atk_max': '5', 'val': '0', 'name': 'dagger of bluntness', 'rng': '3'}}
正如你所看到的,这里只有一个项目。在其他情况下,我有两个,尽管我实际上列出了3个项目。为什么会发生这种情况,以及如何获取字典中的所有3项

谢谢! :P

编辑:这是药水的数据,以防你想知道

 elif line.split()[0] == "POTION":
        _, id, name, hp_bonus, atk_bonus, range_bonus, ac_bonus, str_bonus, con_bonus, dex_bonus, int_bonus, wis_bonus, cha_bonus, wt, val = line.split()
治疗药剂在文件中看起来像这样:

POTION 1 potion_of_healing 20 0 0 0 0 0 0 0 0 0 0.1 2
每一行
都已经包含下一行,因为遍历类似文件的对象(例如,使用for循环)会导致它逐行遍历

在循环的每次迭代中,文件指针前进一行(类似文件的对象,虽然可以倒带,但会跟踪它们最后访问的位置),然后在完成任何操作之前,
readline()

要解决此问题,请直接在循环体中使用循环变量(
每行),并在.readline()中禁用
文件

每一行
都已经包含下一行,因为遍历类似文件的对象(例如,使用for循环)会导致它逐行遍历

在循环的每次迭代中,文件指针前进一行(类似文件的对象,虽然可以倒带,但会跟踪它们最后访问的位置),然后在完成任何操作之前,
readline()


要解决此问题,请直接在循环体中使用循环变量(
每行
),并在.readline()中禁用
文件

@noname1014,我知道您知道这一点,但我想指出代码中的一些问题(在某些特殊情况下可能会发生这种情况,例如,如果您将文件名
items.txt
更改为
new_items.txt
ravel_fruits.txt
等)和一些建议

不要在Windows中使用
\
作为路径分隔符。请使用
\
,否则您可能会遇到问题。
\code\time\u items.txt
将被评估为
\code imeems.txt
,因为
\t
是此处的选项卡

如果
\
后跟任何字符
A
p
n
t
等不构造转义序列,如
\n
\t
\f
\r
\b
等,则使用
仅在少数情况下有效

请看下面的示例进行说明

>>> import os
>>>
>>> print(os.getcwd() + '\Code\timeitems.txt')
E:\Users\Rishikesh\Python3\Practice\Code        imeitems.txt
>>>
>>> print(os.getcwd() + '\Code\\timeitems.txt')
E:\Users\Rishikesh\Python3\Practice\Code\timeitems.txt
>>>
>>> print(os.getcwd() + '\Code\newitems.txt')
E:\Users\Rishikesh\Python3\Practice\Code
ewitems.txt
>>>
>>> print(os.getcwd() + '\\Code\\newitems.txt')
E:\Users\Rishikesh\Python3\Practice\Code\newitems.txt
>>>
>>> # Do not use it as it may work only in some cases if \ followed by any character does not construct escape sequences.
...
>>> os.getcwd() + '\Code\items.txt'
'E:\\Users\\Rishikesh\\Python3\\Practice\\Code\\items.txt'
>>>
>>> # Use \\ as path separators
...
>>> os.getcwd() + '\\Code\\items.txt'
'E:\\Users\\Rishikesh\\Python3\\Practice\\Code\\items.txt'
>>>
>>> print(os.getcwd() + '\Code\items.txt')
E:\Users\Rishikesh\Python3\Practice\Code\items.txt
>>>
>>> print(os.getcwd() + '\\Code\\items.txt')
E:\Users\Rishikesh\Python3\Practice\Code\items.txt
>>>
如果您的字典非常庞大,并且在查看它的项目时遇到任何问题,请使用json模块对其进行处理,它有一个名为
dumps()
的函数,用于漂亮地打印
列表
字典
对象

可以将
import
语句放在函数中,但将其放在顶部是一种python方式()。它适用于在同一模块中具有多个函数的大型应用程序

使用with语句打开文件,在这种情况下不需要关闭文件

你的代码很好,我只是修改了它如下

import os
global items
import json

def items_get():
    items = {
        "weapon":{},
        "armour":{},
        "potion":{},
        "misc":{}
    }

    # Do not use \ as path separators in Windows. Use \\ (\t, \n, \' have speacial meanings)
    file_dir = ( os.getcwd() + '\\Code\\items.txt' )

    with open( file_dir, 'r') as file_in:
        lines = file_in.readlines();
        # ['WEAPON 3 sword_of_eventual_obsolescence 6 10 2 0 10\n', 'WEAPON 4 dagger_of_bluntness 2 5 3 1 0\n', 'WEAPON 5 sword_of_extreme_flimsiness 3 8 3 7 0']

        for each_line in lines:
            # Use strip() to remove any leading/trailing whitespaces (\n, \t, spaces etc.)
            line = each_line.strip().split(' ');

            if line[0] == "WEAPON":
                weapon_id = line[1]
                name = line[2]
                attack_min = line[3]
                attack_max = line[4]
                range = line[5]
                weight = line[6]
                value = line[7]

                weapon_data = {
                    "name": name.replace('_', ' '),
                    "atk_min": attack_min,
                    "atk_max": attack_max,
                    "rng": range,
                    "wt": weight,
                    "val": value,
                }
                items["weapon"][weapon_id] = {}
                items["weapon"][weapon_id].update(weapon_data)
    return items 

# Calling items_get() to get dictionary
items = items_get();
# Pretty printing dictionary using json.dumps()
print(json.dumps(items, indent=4))
»输出

{
    "weapon": {
        "3": {
            "name": "sword of eventual obsolescence",
            "atk_min": "6",
            "atk_max": "10",
            "rng": "2",
            "wt": "0",
            "val": "10"
        },
        "4": {
            "name": "dagger of bluntness",
            "atk_min": "2",
            "atk_max": "5",
            "rng": "3",
            "wt": "1",
            "val": "0"
        },
        "5": {
            "name": "sword of extreme flimsiness",
            "atk_min": "3",
            "atk_max": "8",
            "rng": "3",
            "wt": "7",
            "val": "0"
        }
    },
    "armour": {},
    "potion": {},
    "misc": {}
}

@noname1014,我知道您知道这一点,但我想指出代码中的一些问题(在某些特殊情况下可能会出现这些问题,例如,如果您将文件名
items.txt
更改为
new_items.txt
稀有水果.txt
等)和一些建议

不要在Windows中使用
\
作为路径分隔符。请使用
\
,否则您可能会遇到问题。
\code\time\u items.txt
将被评估为
\code imeems.txt
,因为
\t
是此处的选项卡

如果
\
后跟任何字符
A
p
n
t
等不构造转义序列,如
\n
\t
\f
\r
\b
等,则使用
仅在少数情况下有效

请看下面的示例进行说明

>>> import os
>>>
>>> print(os.getcwd() + '\Code\timeitems.txt')
E:\Users\Rishikesh\Python3\Practice\Code        imeitems.txt
>>>
>>> print(os.getcwd() + '\Code\\timeitems.txt')
E:\Users\Rishikesh\Python3\Practice\Code\timeitems.txt
>>>
>>> print(os.getcwd() + '\Code\newitems.txt')
E:\Users\Rishikesh\Python3\Practice\Code
ewitems.txt
>>>
>>> print(os.getcwd() + '\\Code\\newitems.txt')
E:\Users\Rishikesh\Python3\Practice\Code\newitems.txt
>>>
>>> # Do not use it as it may work only in some cases if \ followed by any character does not construct escape sequences.
...
>>> os.getcwd() + '\Code\items.txt'
'E:\\Users\\Rishikesh\\Python3\\Practice\\Code\\items.txt'
>>>
>>> # Use \\ as path separators
...
>>> os.getcwd() + '\\Code\\items.txt'
'E:\\Users\\Rishikesh\\Python3\\Practice\\Code\\items.txt'
>>>
>>> print(os.getcwd() + '\Code\items.txt')
E:\Users\Rishikesh\Python3\Practice\Code\items.txt
>>>
>>> print(os.getcwd() + '\\Code\\items.txt')
E:\Users\Rishikesh\Python3\Practice\Code\items.txt
>>>
如果您的字典非常庞大,并且在查看它的项目时遇到任何问题,请使用json模块对其进行处理,它有一个名为
dumps()
的函数,用于漂亮地打印
列表
字典
对象

可以将
import
语句放在函数中,但将其放在顶部是一种python方式()。它适用于在同一模块中具有多个函数的大型应用程序

使用with语句打开文件,在这种情况下不需要关闭文件

你的代码很好,我只是修改了它如下

import os
global items
import json

def items_get():
    items = {
        "weapon":{},
        "armour":{},
        "potion":{},
        "misc":{}
    }

    # Do not use \ as path separators in Windows. Use \\ (\t, \n, \' have speacial meanings)
    file_dir = ( os.getcwd() + '\\Code\\items.txt' )

    with open( file_dir, 'r') as file_in:
        lines = file_in.readlines();
        # ['WEAPON 3 sword_of_eventual_obsolescence 6 10 2 0 10\n', 'WEAPON 4 dagger_of_bluntness 2 5 3 1 0\n', 'WEAPON 5 sword_of_extreme_flimsiness 3 8 3 7 0']

        for each_line in lines:
            # Use strip() to remove any leading/trailing whitespaces (\n, \t, spaces etc.)
            line = each_line.strip().split(' ');

            if line[0] == "WEAPON":
                weapon_id = line[1]
                name = line[2]
                attack_min = line[3]
                attack_max = line[4]
                range = line[5]
                weight = line[6]
                value = line[7]

                weapon_data = {
                    "name": name.replace('_', ' '),
                    "atk_min": attack_min,
                    "atk_max": attack_max,
                    "rng": range,
                    "wt": weight,
                    "val": value,
                }
                items["weapon"][weapon_id] = {}
                items["weapon"][weapon_id].update(weapon_data)
    return items 

# Calling items_get() to get dictionary
items = items_get();
# Pretty printing dictionary using json.dumps()
print(json.dumps(items, indent=4))
»输出

{
    "weapon": {
        "3": {
            "name": "sword of eventual obsolescence",
            "atk_min": "6",
            "atk_max": "10",
            "rng": "2",
            "wt": "0",
            "val": "10"
        },
        "4": {
            "name": "dagger of bluntness",
            "atk_min": "2",
            "atk_max": "5",
            "rng": "3",
            "wt": "1",
            "val": "0"
        },
        "5": {
            "name": "sword of extreme flimsiness",
            "atk_min": "3",
            "atk_max": "8",
            "rng": "3",
            "wt": "7",
            "val": "0"
        }
    },
    "armour": {},
    "potion": {},
    "misc": {}
}

物品[“武器”][武器id]=武器数据
将为您节省一行代码。伟大的武器名称
武器最终会过时
还有,
,武器id,名称,攻击最小值,攻击最大值,射程,重量,值=行。拆分()
而不是手动写出每个索引
物品[“武器”][武器id]=武器数据
将为您节省一行代码。伟大的武器名称
最终过时的宝剑
还有,
,武器id,名称,攻击最小值,攻击最大值,射程,重量,值=line.split()
而不是手动写出每个索引非常感谢!这很有效,我只花了10秒就修好了!非常感谢!这很有效,我只花了10秒就修好了!