Python-AttributeError:"int"对象在尝试调用NetworkX上的GML文件时没有属性'decode'"



前提・我想要实现的目标

我将使用Python来读取GML文件。

错误消息

Traceback (most recent call last):
File "firstgml.py", line 9, in <module>
G = nx.read_gml(gml_path)
File "<decorator-gen-434>", line 2, in read_gml
File "/Users/XXXX/.pyenv/versions/3.8.5/lib/python3.8/site-packages/networkx/utils/decorators.py", line 227, in _open_file
result = func_to_be_decorated(*new_args, **kwargs)
File "/Users/XXXX/.pyenv/versions/3.8.5/lib/python3.8/site-packages/networkx/readwrite/gml.py", line 218, in read_gml
G = parse_gml_lines(filter_lines(path), label, destringizer)
File "/Users/XXXX/.pyenv/versions/3.8.5/lib/python3.8/site-packages/networkx/readwrite/gml.py", line 398, in parse_gml_lines
graph = parse_graph()
File "/Users/XXXX/.pyenv/versions/3.8.5/lib/python3.8/site-packages/networkx/readwrite/gml.py", line 387, in parse_graph
curr_token, dct = parse_kv(next(tokens))
File "/Users/XXXX/.pyenv/versions/3.8.5/lib/python3.8/site-packages/networkx/readwrite/gml.py", line 315, in tokenize
for line in lines:
File "/Users/XXXX/.pyenv/versions/3.8.5/lib/python3.8/site-packages/networkx/readwrite/gml.py", line 209, in filter_lines
line = line.decode('ascii')
AttributeError: 'int' object has no attribute 'decode'

对应源代码

import numpy as np
import networkx as nx
gml_path = "XXXX.gml"
gml_path = gml_path.encode("utf-8")
G = nx.read_gml(gml_path)
X = np.array(nx.to_numpy_matrix(G))
print(nx.is_directed(G))

我尝试了什么

我把编码字符代码改成了ascii等等,但是我得到了一个错误。

补充信息(固件/工具版本等(

Python 3.85

networkx 2.1

numpy 1.19.2

这是错误的部分。

gml_path = "XXXX.gml"
gml_path = gml_path.encode("utf-8")
G = nx.read_gml(gml_path)

您不应该对文件名进行编码。read_gml采用文件名或文件句柄。当你传递编码的gml_path时,它认为它是一个打开的文件,所以它会对它进行迭代。当它进行line.decode('ascii')时,line变量包含b'X',它会传递到数字88。

gml_path = "XXXX.gml"
gml_path = gml_path.encode("utf-8")
print(gml_path[0])
>>> 88

您之前遇到的错误:"NetworkXError: input is not ASCII-encoded"是因为您的文件没有正确编码,而不是您的文件路径。您应该做的是删除这行gml_path = gml_path.encode("utf-8"),并使用另一个工具或使用Python对GML文件进行编码。

最新更新