gpt4 book ai didi

即使我导入了集合,也没有定义 python 全局名称 'collections'

转载 作者:太空狗 更新时间:2023-10-30 01:54:16 24 4
gpt4 key购买 nike

以下是config.py:

from collections import OrderedDict
def test_config(fileName):
tp_dict = collections.OrderedDict()
with open("../../config/" + fileName, 'r') as myfile:
file_str = myfile.read().replace(' ', '').split('\n')
tp_list = []
for i, x in enumerate(file_str):
x = x.strip()
try:
key = x[:x.index(':')].strip()
value = x[x.index(':')+1:]
if key == 'testpoint':
pass
else:
tp_dict[key] = value.strip().split(',')
except ValueError,e:
pass
if i % 4 == 0 and i != 0:
tp_list.append(tp_dict.copy())
return tp_list

我正在另一个文件 test.py 中使用该函数:

import config
a = config.test_config('test.txt')

NameError: global name 'collections' is not defined

但如果我将整个代码从 config.py 复制粘贴到 test.py 的顶部,然后使用该函数,那么我没有错误(请参见下面的代码)。有人可以向我解释一下吗?我很困惑。非常感谢你!

"""
This is test.py
"""
from collections import OrderedDict
def test_config(fileName):
tp_dict = collections.OrderedDict()
with open("../../config/" + fileName, 'r') as myfile:
file_str = myfile.read().replace(' ', '').split('\n')
tp_list = []
for i, x in enumerate(file_str):
x = x.strip()
try:
key = x[:x.index(':')].strip()
value = x[x.index(':')+1:]
if key == 'testpoint':
pass
else:
tp_dict[key] = value.strip().split(',')
except ValueError,e:
pass
if i % 4 == 0 and i != 0:
tp_list.append(tp_dict.copy())
return tp_list
a = test_config('test.txt')

最佳答案

from collections import OrderedDict 更改为 import collections

关于即使我导入了集合,也没有定义 python 全局名称 'collections',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28031880/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com