简体   繁体   中英

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. Please ask for any more info if you need it.

G is a networkx graph, such that:

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 . 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. To check the type of an object in Python, you can pass an object to the built in type() function

>>> 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['spam']
{}

To explain why you got this particular exception - in Python you can access each character in a string via its index. 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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