Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/19.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 AttributeError:';dict';对象没有属性';从'开始;何时';dict';列表中_Python_Python 3.x - Fatal编程技术网

Python AttributeError:';dict';对象没有属性';从'开始;何时';dict';列表中

Python AttributeError:';dict';对象没有属性';从'开始;何时';dict';列表中,python,python-3.x,Python,Python 3.x,我正在从列表类型的json文件中的数据中提取哈希标记。这对我的一些文件有效,但对列表中包含“dict”的其他文件无效。我是否可以修改我的代码以适应这种情况?我已经包括了一个例子,它的工作和一个例子,它没有 file_name = 'twitter1.json' with open(file_path + file_name) as json_file: data = json.load(json_file) data ['http://b8nicktof280.com/skoex/po2

我正在从列表类型的json文件中的数据中提取哈希标记。这对我的一些文件有效,但对列表中包含“dict”的其他文件无效。我是否可以修改我的代码以适应这种情况?我已经包括了一个例子,它的工作和一个例子,它没有

file_name = 'twitter1.json'
with open(file_path + file_name) as json_file:
    data = json.load(json_file)
data
['http://b8nicktof280.com/skoex/po2.php?l=deof', 
'http://dwillow100bc.com/skoex/po2.php?l=deof',
'#ursnif', '#malspam']

type(data)
list

#Extract the tags for use in api post assignment
tags = [tag for tag in data if tag.startswith('#')]
tags
['#ursnif','#malspam']
这将毫无问题地提取标记

但对于下一个示例,数据类型也是一个列表,但其中有{}导致错误:
AttributeError:'dict'对象没有属性'startswith'

file_name = 'twitter2.json'
with open(file_path + file_name) as json_file:
    data = json.load(json_file)
data
['t.co', '', '103.126.6.93', '#twitter', {'Address': '103.126.6.93'}]

type(data)
list

#Extract the tags for use in api post assignment
tags = [tag for tag in data if tag.startswith('#')]
AttributeError: 'dict' object has no attribute 'startswith'

最简单的解决方案是忽略
数据
中非字符串的任何项:

tags = [tag for tag in data if isinstance(tag, str) and tag.startswith('#')]

最简单的解决方案是忽略
数据
中非字符串的任何项:

tags = [tag for tag in data if isinstance(tag, str) and tag.startswith('#')]

在最后一个列表中检查标记的数据类型,并相应地追加它

tags = [tag if isinstance(tag, list) else list(tag.values())[0] for tag in data]    
然后在标记列表中使用startswith():

li = [tag for tag in tags if tag.startswith(‘#’)].   

对于标签,我假设字典中只有一个值,如果不是这样,我们可以在加入所有dict.values()后生成一个字符串。

检查最后一个列表中标签的数据类型,并相应地追加它

tags = [tag if isinstance(tag, list) else list(tag.values())[0] for tag in data]    
然后在标记列表中使用startswith():

li = [tag for tag in tags if tag.startswith(‘#’)].   

对于标记,我假设字典中只有一个值,如果不是这样的话,我们可以在连接所有dict.values()之后生成一个字符串。

{'Address':'103.126.6.93'}
这是dict(它没有python正确指出的属性
startswith
)。您的
json.loads
创建了它。因此,您的文件在该位置必须有一个嵌套的json对象。
{'Address':'103.126.6.93}
这是dict(它没有python正确指出的属性
startswith
)。您的
json.loads
创建了它。所以你的文件必须在那个位置有一个嵌套的json对象。这是一个Python 3问题,所以应该是
str
而不是
basestring
,不是吗?这是一个Python 3问题,所以应该是
str
而不是
basestring
,不是吗?