Python-AttributeError: 'int' object has no attribute 'decode'" when trying to call the GML file on NetworkX

Python-AttributeError: 'int' object has no attribute 'decode'" when trying to call the GML file on NetworkX

前提·我要达到的目标

我将使用 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 文件进行编码