[英]Error in Python and network X - TypeError: string indices must be integers, not str
I'm pretty new to coding, and am still exploring the endless joys of using Python. 我对编码非常陌生,并且仍在探索使用Python带来的无穷乐趣。 Please ask for any more info if you need it.
如果需要,请索取更多信息。
G is a networkx graph, such that: G是一个networkx图,例如:
G = nx.Graph(nx.read_dot('C:\Users\...\myCode.dot'))
The rest of my code rearranges the order the atoms/nodes in my networkx graph.I want to convert the output i get from my graph, G, into an xyz file so I can view it with an appropriate software package . 我其余的代码重新排列了networkx图中原子/节点的顺序。我想将从图G中获得的输出转换为xyz文件,以便可以使用适当的软件包进行查看。 But i'm left with the error message.
但是我留下了错误信息。
write(str(node['species'])+' '+str(node['x'])+' '+str(node['y'])+' '+str(node['z'])+'\n')
TypeError: string indices must be integers, not str
Here's the code below. 这是下面的代码。
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()
Can someone show me how i can fix this? 有人可以告诉我如何解决此问题吗?
You are getting that exception because node
is a string, but you are trying to access elements in the node
object as if it were a dictionary. 因为
node
是一个字符串,所以您得到该异常,但是您试图像访问字典一样访问node
对象中的元素。 To check the type of an object in Python, you can pass an object to the built in type()
function 要在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'>
So you don't want to iterate over G, instead you probably want to access nodes via their key from the graph object directly. 因此,您不想遍历G,相反,您可能想直接通过图对象通过其键访问节点。
>>> G['spam']
{}
To explain why you got this particular exception - in Python you can access each character in a string via its index. 为了解释为什么会出现此特定异常-在Python中,您可以通过字符串的索引访问字符串中的每个字符。 For example
例如
>>> node = "hello"
>>> node[0]
"h"
>>> node[4]
"o"
If you pass any other object, for example a string, you'll get a TypeError. 如果传递任何其他对象(例如字符串),则会收到TypeError。
>>> node["x"]
TypeError: string indices must be integers, not str
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.