繁体   English   中英

Python和网络X中的错误-TypeError:字符串索引必须是整数,而不是str

[英]Error in Python and network X - TypeError: string indices must be integers, not str

我对编码非常陌生,并且仍在探索使用Python带来的无穷乐趣。 如果需要,请索取更多信息。

G是一个networkx图,例如:

G = nx.Graph(nx.read_dot('C:\Users\...\myCode.dot'))

我其余的代码重新排列了networkx图中原子/节点的顺序。我想将从图G中获得的输出转换为xyz文件,以便可以使用适当的软件包进行查看。 但是我留下了错误信息。

write(str(node['species'])+' '+str(node['x'])+' '+str(node['y'])+' '+str(node['z'])+'\n')
TypeError: string indices must be integers, not str

这是下面的代码。

def writeGraphToXYZ(myGraph,myFilename):

""" Writes myGraph to myFilename as a .xyz file to allow easier visualisation of the                              graph.
.xyz files always start with the number of atoms on the first line,
followed by a comment string on the next line,
and then atom information on all successive lines.
"""
f = open(myFilename,'w') 
f.write(str(len(G))+'\n') # prints number of atoms followed by newline ('\n')
f.write('Atoms. File created from networkx graph by IsingModel.py\n')
for node in G:
    f.write(str(node['species'])+' '+str(node['x'])+' '+str(node['y'])+' '+str(node['z'])+'\n')
f.close()

有人可以告诉我如何解决此问题吗?

因为node是一个字符串,所以您得到该异常,但是您试图像访问字典一样访问node对象中的元素。 要在Python中检查对象的类型,可以将对象传递给内置的type()函数

>>> from networkx import nx
>>> G = nx.Graph()
>>> G.add_node("span")
>>> for node in G:
        print node
        print type(node)
"span"
<type 'str'>

因此,您不想遍历G,相反,您可能想直接通过图对象通过其键访问节点。

>>> G['spam']
{}

为了解释为什么会出现此特定异常-在Python中,您可以通过字符串的索引访问字符串中的每个字符。 例如

>>> node = "hello"
>>> node[0]
"h"
>>> node[4]
"o"

如果传递任何其他对象(例如字符串),则会收到TypeError。

>>> node["x"]
TypeError: string indices must be integers, not str

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM