We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Pajek export assumes Graph node's id attribute to be int castable
In pajek export it reads https://github.com/networkx/networkx/blob/b0ca6ce081cc6e66d509c5f7fed60728da821c25/networkx/readwrite/pajek.py#L57

I was wondering, since NetworkX supports arbitrary Python objects as Graph nodes where does the assumption come from that a node's `id` attribute is `int` castable? An objects `id` attribute would have nothing to do with Python's builtin `id()`. But I'm not familiar with the Pajek file format so don't know about the relevance and special treatment of `id` in it.

I was working with a Graph whose node's `id` attribute happened to be a string. For it Pajek export failed with
```
ValueError: invalid literal for int() with base 10: 'arn:aws:iam::579763146468:role/aws-service-role/trustedadvisor.amazonaws.com/AWSServiceRoleForTrustedAdvisor'
```


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `networkx/readwrite/pajek.py`
Content:
```
1 """
2 *****
3 Pajek
4 *****
5 Read graphs in Pajek format.
6 
7 This implementation handles directed and undirected graphs including
8 those with self loops and parallel edges.
9 
10 Format
11 ------
12 See http://vlado.fmf.uni-lj.si/pub/networks/pajek/doc/draweps.htm
13 for format information.
14 
15 """
16 
17 import warnings
18 
19 import networkx as nx
20 from networkx.utils import open_file
21 
22 __all__ = ['read_pajek', 'parse_pajek', 'generate_pajek', 'write_pajek']
23 
24 
25 def generate_pajek(G):
26     """Generate lines in Pajek graph format.
27 
28     Parameters
29     ----------
30     G : graph
31        A Networkx graph
32 
33     References
34     ----------
35     See http://vlado.fmf.uni-lj.si/pub/networks/pajek/doc/draweps.htm
36     for format information.
37     """
38     if G.name == '':
39         name = 'NetworkX'
40     else:
41         name = G.name
42     # Apparently many Pajek format readers can't process this line
43     # So we'll leave it out for now.
44     # yield '*network %s'%name
45 
46     # write nodes with attributes
47     yield f"*vertices {G.order()}"
48     nodes = list(G)
49     # make dictionary mapping nodes to integers
50     nodenumber = dict(zip(nodes, range(1, len(nodes) + 1)))
51     for n in nodes:
52         # copy node attributes and pop mandatory attributes
53         # to avoid duplication.
54         na = G.nodes.get(n, {}).copy()
55         x = na.pop('x', 0.0)
56         y = na.pop('y', 0.0)
57         id = int(na.pop('id', nodenumber[n]))
58         nodenumber[n] = id
59         shape = na.pop('shape', 'ellipse')
60         s = ' '.join(map(make_qstr, (id, n, x, y, shape)))
61         # only optional attributes are left in na.
62         for k, v in na.items():
63             if isinstance(v, str) and v.strip() != '':
64                 s += f" {make_qstr(k)} {make_qstr(v)}"
65             else:
66                 warnings.warn(f"Node attribute {k} is not processed. {('Empty attribute' if isinstance(v, str) else 'Non-string attribute')}.")
67         yield s
68 
69     # write edges with attributes
70     if G.is_directed():
71         yield '*arcs'
72     else:
73         yield '*edges'
74     for u, v, edgedata in G.edges(data=True):
75         d = edgedata.copy()
76         value = d.pop('weight', 1.0)  # use 1 as default edge value
77         s = ' '.join(map(make_qstr, (nodenumber[u], nodenumber[v], value)))
78         for k, v in d.items():
79             if isinstance(v, str) and v.strip() != '':
80                 s += f" {make_qstr(k)} {make_qstr(v)}"
81             else:
82                 warnings.warn(f"Edge attribute {k} is not processed. {('Empty attribute' if isinstance(v, str) else 'Non-string attribute')}.")
83         yield s
84 
85 
86 @open_file(1, mode='wb')
87 def write_pajek(G, path, encoding='UTF-8'):
88     """Write graph in Pajek format to path.
89 
90     Parameters
91     ----------
92     G : graph
93        A Networkx graph
94     path : file or string
95        File or filename to write.
96        Filenames ending in .gz or .bz2 will be compressed.
97 
98     Examples
99     --------
100     >>> G = nx.path_graph(4)
101     >>> nx.write_pajek(G, "test.net")
102 
103     Warnings
104     --------
105     Optional node attributes and edge attributes must be non-empty strings.
106     Otherwise it will not be written into the file. You will need to
107     convert those attributes to strings if you want to keep them.
108 
109     References
110     ----------
111     See http://vlado.fmf.uni-lj.si/pub/networks/pajek/doc/draweps.htm
112     for format information.
113     """
114     for line in generate_pajek(G):
115         line += '\n'
116         path.write(line.encode(encoding))
117 
118 
119 @open_file(0, mode='rb')
120 def read_pajek(path, encoding='UTF-8'):
121     """Read graph in Pajek format from path.
122 
123     Parameters
124     ----------
125     path : file or string
126        File or filename to write.
127        Filenames ending in .gz or .bz2 will be uncompressed.
128 
129     Returns
130     -------
131     G : NetworkX MultiGraph or MultiDiGraph.
132 
133     Examples
134     --------
135     >>> G = nx.path_graph(4)
136     >>> nx.write_pajek(G, "test.net")
137     >>> G = nx.read_pajek("test.net")
138 
139     To create a Graph instead of a MultiGraph use
140 
141     >>> G1 = nx.Graph(G)
142 
143     References
144     ----------
145     See http://vlado.fmf.uni-lj.si/pub/networks/pajek/doc/draweps.htm
146     for format information.
147     """
148     lines = (line.decode(encoding) for line in path)
149     return parse_pajek(lines)
150 
151 
152 def parse_pajek(lines):
153     """Parse Pajek format graph from string or iterable.
154 
155     Parameters
156     ----------
157     lines : string or iterable
158        Data in Pajek format.
159 
160     Returns
161     -------
162     G : NetworkX graph
163 
164     See Also
165     --------
166     read_pajek()
167 
168     """
169     import shlex
170     # multigraph=False
171     if isinstance(lines, str):
172         lines = iter(lines.split('\n'))
173     lines = iter([line.rstrip('\n') for line in lines])
174     G = nx.MultiDiGraph()  # are multiedges allowed in Pajek? assume yes
175     labels = []  # in the order of the file, needed for matrix
176     while lines:
177         try:
178             l = next(lines)
179         except:  # EOF
180             break
181         if l.lower().startswith("*network"):
182             try:
183                 label, name = l.split(None, 1)
184             except ValueError:
185                 # Line was not of the form:  *network NAME
186                 pass
187             else:
188                 G.graph['name'] = name
189         elif l.lower().startswith("*vertices"):
190             nodelabels = {}
191             l, nnodes = l.split()
192             for i in range(int(nnodes)):
193                 l = next(lines)
194                 try:
195                     splitline = [x.decode('utf-8') for x in
196                                  shlex.split(str(l).encode('utf-8'))]
197                 except AttributeError:
198                     splitline = shlex.split(str(l))
199                 id, label = splitline[0:2]
200                 labels.append(label)
201                 G.add_node(label)
202                 nodelabels[id] = label
203                 G.nodes[label]['id'] = id
204                 try:
205                     x, y, shape = splitline[2:5]
206                     G.nodes[label].update({'x': float(x),
207                                            'y': float(y),
208                                            'shape': shape})
209                 except:
210                     pass
211                 extra_attr = zip(splitline[5::2], splitline[6::2])
212                 G.nodes[label].update(extra_attr)
213         elif l.lower().startswith("*edges") or l.lower().startswith("*arcs"):
214             if l.lower().startswith("*edge"):
215                 # switch from multidigraph to multigraph
216                 G = nx.MultiGraph(G)
217             if l.lower().startswith("*arcs"):
218                 # switch to directed with multiple arcs for each existing edge
219                 G = G.to_directed()
220             for l in lines:
221                 try:
222                     splitline = [x.decode('utf-8') for x in
223                                  shlex.split(str(l).encode('utf-8'))]
224                 except AttributeError:
225                     splitline = shlex.split(str(l))
226 
227                 if len(splitline) < 2:
228                     continue
229                 ui, vi = splitline[0:2]
230                 u = nodelabels.get(ui, ui)
231                 v = nodelabels.get(vi, vi)
232                 # parse the data attached to this edge and put in a dictionary
233                 edge_data = {}
234                 try:
235                     # there should always be a single value on the edge?
236                     w = splitline[2:3]
237                     edge_data.update({'weight': float(w[0])})
238                 except:
239                     pass
240                     # if there isn't, just assign a 1
241 #                    edge_data.update({'value':1})
242                 extra_attr = zip(splitline[3::2], splitline[4::2])
243                 edge_data.update(extra_attr)
244                 # if G.has_edge(u,v):
245                 #     multigraph=True
246                 G.add_edge(u, v, **edge_data)
247         elif l.lower().startswith("*matrix"):
248             G = nx.DiGraph(G)
249             adj_list = ((labels[row], labels[col], {'weight': int(data)})
250                         for (row, line) in enumerate(lines)
251                         for (col, data) in enumerate(line.split())
252                         if int(data) != 0)
253             G.add_edges_from(adj_list)
254 
255     return G
256 
257 
258 def make_qstr(t):
259     """Returns the string representation of t.
260     Add outer double-quotes if the string has a space.
261     """
262     if not isinstance(t, str):
263         t = str(t)
264     if " " in t:
265         t = f'"{t}"'
266     return t
267
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/networkx/readwrite/pajek.py b/networkx/readwrite/pajek.py
--- a/networkx/readwrite/pajek.py
+++ b/networkx/readwrite/pajek.py
@@ -54,7 +54,12 @@
         na = G.nodes.get(n, {}).copy()
         x = na.pop('x', 0.0)
         y = na.pop('y', 0.0)
-        id = int(na.pop('id', nodenumber[n]))
+        try:
+            id = int(na.pop('id', nodenumber[n]))
+        except ValueError as e:
+            e.args += (("Pajek format requires 'id' to be an int()."
+                        " Refer to the 'Relabeling nodes' section."),)
+            raise
         nodenumber[n] = id
         shape = na.pop('shape', 'ellipse')
         s = ' '.join(map(make_qstr, (id, n, x, y, shape)))

{"golden_diff": "diff --git a/networkx/readwrite/pajek.py b/networkx/readwrite/pajek.py\n--- a/networkx/readwrite/pajek.py\n+++ b/networkx/readwrite/pajek.py\n@@ -54,7 +54,12 @@\n         na = G.nodes.get(n, {}).copy()\n         x = na.pop('x', 0.0)\n         y = na.pop('y', 0.0)\n-        id = int(na.pop('id', nodenumber[n]))\n+        try:\n+            id = int(na.pop('id', nodenumber[n]))\n+        except ValueError as e:\n+            e.args += ((\"Pajek format requires 'id' to be an int().\"\n+                        \" Refer to the 'Relabeling nodes' section.\"),)\n+            raise\n         nodenumber[n] = id\n         shape = na.pop('shape', 'ellipse')\n         s = ' '.join(map(make_qstr, (id, n, x, y, shape)))\n", "issue": "Pajek export assumes Graph node's id attribute to be int castable\nIn pajek export it reads https://github.com/networkx/networkx/blob/b0ca6ce081cc6e66d509c5f7fed60728da821c25/networkx/readwrite/pajek.py#L57\r\n\r\nI was wondering, since NetworkX supports arbitrary Python objects as Graph nodes where does the assumption come from that a node's `id` attribute is `int` castable? An objects `id` attribute would have nothing to do with Python's builtin `id()`. But I'm not familiar with the Pajek file format so don't know about the relevance and special treatment of `id` in it.\r\n\r\nI was working with a Graph whose node's `id` attribute happened to be a string. For it Pajek export failed with\r\n```\r\nValueError: invalid literal for int() with base 10: 'arn:aws:iam::579763146468:role/aws-service-role/trustedadvisor.amazonaws.com/AWSServiceRoleForTrustedAdvisor'\r\n```\r\n\n", "before_files": [{"content": "\"\"\"\n*****\nPajek\n*****\nRead graphs in Pajek format.\n\nThis implementation handles directed and undirected graphs including\nthose with self loops and parallel edges.\n\nFormat\n------\nSee http://vlado.fmf.uni-lj.si/pub/networks/pajek/doc/draweps.htm\nfor format information.\n\n\"\"\"\n\nimport warnings\n\nimport networkx as nx\nfrom networkx.utils import open_file\n\n__all__ = ['read_pajek', 'parse_pajek', 'generate_pajek', 'write_pajek']\n\n\ndef generate_pajek(G):\n    \"\"\"Generate lines in Pajek graph format.\n\n    Parameters\n    ----------\n    G : graph\n       A Networkx graph\n\n    References\n    ----------\n    See http://vlado.fmf.uni-lj.si/pub/networks/pajek/doc/draweps.htm\n    for format information.\n    \"\"\"\n    if G.name == '':\n        name = 'NetworkX'\n    else:\n        name = G.name\n    # Apparently many Pajek format readers can't process this line\n    # So we'll leave it out for now.\n    # yield '*network %s'%name\n\n    # write nodes with attributes\n    yield f\"*vertices {G.order()}\"\n    nodes = list(G)\n    # make dictionary mapping nodes to integers\n    nodenumber = dict(zip(nodes, range(1, len(nodes) + 1)))\n    for n in nodes:\n        # copy node attributes and pop mandatory attributes\n        # to avoid duplication.\n        na = G.nodes.get(n, {}).copy()\n        x = na.pop('x', 0.0)\n        y = na.pop('y', 0.0)\n        id = int(na.pop('id', nodenumber[n]))\n        nodenumber[n] = id\n        shape = na.pop('shape', 'ellipse')\n        s = ' '.join(map(make_qstr, (id, n, x, y, shape)))\n        # only optional attributes are left in na.\n        for k, v in na.items():\n            if isinstance(v, str) and v.strip() != '':\n                s += f\" {make_qstr(k)} {make_qstr(v)}\"\n            else:\n                warnings.warn(f\"Node attribute {k} is not processed. {('Empty attribute' if isinstance(v, str) else 'Non-string attribute')}.\")\n        yield s\n\n    # write edges with attributes\n    if G.is_directed():\n        yield '*arcs'\n    else:\n        yield '*edges'\n    for u, v, edgedata in G.edges(data=True):\n        d = edgedata.copy()\n        value = d.pop('weight', 1.0)  # use 1 as default edge value\n        s = ' '.join(map(make_qstr, (nodenumber[u], nodenumber[v], value)))\n        for k, v in d.items():\n            if isinstance(v, str) and v.strip() != '':\n                s += f\" {make_qstr(k)} {make_qstr(v)}\"\n            else:\n                warnings.warn(f\"Edge attribute {k} is not processed. {('Empty attribute' if isinstance(v, str) else 'Non-string attribute')}.\")\n        yield s\n\n\n@open_file(1, mode='wb')\ndef write_pajek(G, path, encoding='UTF-8'):\n    \"\"\"Write graph in Pajek format to path.\n\n    Parameters\n    ----------\n    G : graph\n       A Networkx graph\n    path : file or string\n       File or filename to write.\n       Filenames ending in .gz or .bz2 will be compressed.\n\n    Examples\n    --------\n    >>> G = nx.path_graph(4)\n    >>> nx.write_pajek(G, \"test.net\")\n\n    Warnings\n    --------\n    Optional node attributes and edge attributes must be non-empty strings.\n    Otherwise it will not be written into the file. You will need to\n    convert those attributes to strings if you want to keep them.\n\n    References\n    ----------\n    See http://vlado.fmf.uni-lj.si/pub/networks/pajek/doc/draweps.htm\n    for format information.\n    \"\"\"\n    for line in generate_pajek(G):\n        line += '\\n'\n        path.write(line.encode(encoding))\n\n\n@open_file(0, mode='rb')\ndef read_pajek(path, encoding='UTF-8'):\n    \"\"\"Read graph in Pajek format from path.\n\n    Parameters\n    ----------\n    path : file or string\n       File or filename to write.\n       Filenames ending in .gz or .bz2 will be uncompressed.\n\n    Returns\n    -------\n    G : NetworkX MultiGraph or MultiDiGraph.\n\n    Examples\n    --------\n    >>> G = nx.path_graph(4)\n    >>> nx.write_pajek(G, \"test.net\")\n    >>> G = nx.read_pajek(\"test.net\")\n\n    To create a Graph instead of a MultiGraph use\n\n    >>> G1 = nx.Graph(G)\n\n    References\n    ----------\n    See http://vlado.fmf.uni-lj.si/pub/networks/pajek/doc/draweps.htm\n    for format information.\n    \"\"\"\n    lines = (line.decode(encoding) for line in path)\n    return parse_pajek(lines)\n\n\ndef parse_pajek(lines):\n    \"\"\"Parse Pajek format graph from string or iterable.\n\n    Parameters\n    ----------\n    lines : string or iterable\n       Data in Pajek format.\n\n    Returns\n    -------\n    G : NetworkX graph\n\n    See Also\n    --------\n    read_pajek()\n\n    \"\"\"\n    import shlex\n    # multigraph=False\n    if isinstance(lines, str):\n        lines = iter(lines.split('\\n'))\n    lines = iter([line.rstrip('\\n') for line in lines])\n    G = nx.MultiDiGraph()  # are multiedges allowed in Pajek? assume yes\n    labels = []  # in the order of the file, needed for matrix\n    while lines:\n        try:\n            l = next(lines)\n        except:  # EOF\n            break\n        if l.lower().startswith(\"*network\"):\n            try:\n                label, name = l.split(None, 1)\n            except ValueError:\n                # Line was not of the form:  *network NAME\n                pass\n            else:\n                G.graph['name'] = name\n        elif l.lower().startswith(\"*vertices\"):\n            nodelabels = {}\n            l, nnodes = l.split()\n            for i in range(int(nnodes)):\n                l = next(lines)\n                try:\n                    splitline = [x.decode('utf-8') for x in\n                                 shlex.split(str(l).encode('utf-8'))]\n                except AttributeError:\n                    splitline = shlex.split(str(l))\n                id, label = splitline[0:2]\n                labels.append(label)\n                G.add_node(label)\n                nodelabels[id] = label\n                G.nodes[label]['id'] = id\n                try:\n                    x, y, shape = splitline[2:5]\n                    G.nodes[label].update({'x': float(x),\n                                           'y': float(y),\n                                           'shape': shape})\n                except:\n                    pass\n                extra_attr = zip(splitline[5::2], splitline[6::2])\n                G.nodes[label].update(extra_attr)\n        elif l.lower().startswith(\"*edges\") or l.lower().startswith(\"*arcs\"):\n            if l.lower().startswith(\"*edge\"):\n                # switch from multidigraph to multigraph\n                G = nx.MultiGraph(G)\n            if l.lower().startswith(\"*arcs\"):\n                # switch to directed with multiple arcs for each existing edge\n                G = G.to_directed()\n            for l in lines:\n                try:\n                    splitline = [x.decode('utf-8') for x in\n                                 shlex.split(str(l).encode('utf-8'))]\n                except AttributeError:\n                    splitline = shlex.split(str(l))\n\n                if len(splitline) < 2:\n                    continue\n                ui, vi = splitline[0:2]\n                u = nodelabels.get(ui, ui)\n                v = nodelabels.get(vi, vi)\n                # parse the data attached to this edge and put in a dictionary\n                edge_data = {}\n                try:\n                    # there should always be a single value on the edge?\n                    w = splitline[2:3]\n                    edge_data.update({'weight': float(w[0])})\n                except:\n                    pass\n                    # if there isn't, just assign a 1\n#                    edge_data.update({'value':1})\n                extra_attr = zip(splitline[3::2], splitline[4::2])\n                edge_data.update(extra_attr)\n                # if G.has_edge(u,v):\n                #     multigraph=True\n                G.add_edge(u, v, **edge_data)\n        elif l.lower().startswith(\"*matrix\"):\n            G = nx.DiGraph(G)\n            adj_list = ((labels[row], labels[col], {'weight': int(data)})\n                        for (row, line) in enumerate(lines)\n                        for (col, data) in enumerate(line.split())\n                        if int(data) != 0)\n            G.add_edges_from(adj_list)\n\n    return G\n\n\ndef make_qstr(t):\n    \"\"\"Returns the string representation of t.\n    Add outer double-quotes if the string has a space.\n    \"\"\"\n    if not isinstance(t, str):\n        t = str(t)\n    if \" \" in t:\n        t = f'\"{t}\"'\n    return t\n", "path": "networkx/readwrite/pajek.py"}], "after_files": [{"content": "\"\"\"\n*****\nPajek\n*****\nRead graphs in Pajek format.\n\nThis implementation handles directed and undirected graphs including\nthose with self loops and parallel edges.\n\nFormat\n------\nSee http://vlado.fmf.uni-lj.si/pub/networks/pajek/doc/draweps.htm\nfor format information.\n\n\"\"\"\n\nimport warnings\n\nimport networkx as nx\nfrom networkx.utils import open_file\n\n__all__ = ['read_pajek', 'parse_pajek', 'generate_pajek', 'write_pajek']\n\n\ndef generate_pajek(G):\n    \"\"\"Generate lines in Pajek graph format.\n\n    Parameters\n    ----------\n    G : graph\n       A Networkx graph\n\n    References\n    ----------\n    See http://vlado.fmf.uni-lj.si/pub/networks/pajek/doc/draweps.htm\n    for format information.\n    \"\"\"\n    if G.name == '':\n        name = 'NetworkX'\n    else:\n        name = G.name\n    # Apparently many Pajek format readers can't process this line\n    # So we'll leave it out for now.\n    # yield '*network %s'%name\n\n    # write nodes with attributes\n    yield f\"*vertices {G.order()}\"\n    nodes = list(G)\n    # make dictionary mapping nodes to integers\n    nodenumber = dict(zip(nodes, range(1, len(nodes) + 1)))\n    for n in nodes:\n        # copy node attributes and pop mandatory attributes\n        # to avoid duplication.\n        na = G.nodes.get(n, {}).copy()\n        x = na.pop('x', 0.0)\n        y = na.pop('y', 0.0)\n        try:\n            id = int(na.pop('id', nodenumber[n]))\n        except ValueError as e:\n            e.args += ((\"Pajek format requires 'id' to be an int().\"\n                        \" Refer to the 'Relabeling nodes' section.\"),)\n            raise\n        nodenumber[n] = id\n        shape = na.pop('shape', 'ellipse')\n        s = ' '.join(map(make_qstr, (id, n, x, y, shape)))\n        # only optional attributes are left in na.\n        for k, v in na.items():\n            if isinstance(v, str) and v.strip() != '':\n                s += f\" {make_qstr(k)} {make_qstr(v)}\"\n            else:\n                warnings.warn(f\"Node attribute {k} is not processed. {('Empty attribute' if isinstance(v, str) else 'Non-string attribute')}.\")\n        yield s\n\n    # write edges with attributes\n    if G.is_directed():\n        yield '*arcs'\n    else:\n        yield '*edges'\n    for u, v, edgedata in G.edges(data=True):\n        d = edgedata.copy()\n        value = d.pop('weight', 1.0)  # use 1 as default edge value\n        s = ' '.join(map(make_qstr, (nodenumber[u], nodenumber[v], value)))\n        for k, v in d.items():\n            if isinstance(v, str) and v.strip() != '':\n                s += f\" {make_qstr(k)} {make_qstr(v)}\"\n            else:\n                warnings.warn(f\"Edge attribute {k} is not processed. {('Empty attribute' if isinstance(v, str) else 'Non-string attribute')}.\")\n        yield s\n\n\n@open_file(1, mode='wb')\ndef write_pajek(G, path, encoding='UTF-8'):\n    \"\"\"Write graph in Pajek format to path.\n\n    Parameters\n    ----------\n    G : graph\n       A Networkx graph\n    path : file or string\n       File or filename to write.\n       Filenames ending in .gz or .bz2 will be compressed.\n\n    Examples\n    --------\n    >>> G = nx.path_graph(4)\n    >>> nx.write_pajek(G, \"test.net\")\n\n    Warnings\n    --------\n    Optional node attributes and edge attributes must be non-empty strings.\n    Otherwise it will not be written into the file. You will need to\n    convert those attributes to strings if you want to keep them.\n\n    References\n    ----------\n    See http://vlado.fmf.uni-lj.si/pub/networks/pajek/doc/draweps.htm\n    for format information.\n    \"\"\"\n    for line in generate_pajek(G):\n        line += '\\n'\n        path.write(line.encode(encoding))\n\n\n@open_file(0, mode='rb')\ndef read_pajek(path, encoding='UTF-8'):\n    \"\"\"Read graph in Pajek format from path.\n\n    Parameters\n    ----------\n    path : file or string\n       File or filename to write.\n       Filenames ending in .gz or .bz2 will be uncompressed.\n\n    Returns\n    -------\n    G : NetworkX MultiGraph or MultiDiGraph.\n\n    Examples\n    --------\n    >>> G = nx.path_graph(4)\n    >>> nx.write_pajek(G, \"test.net\")\n    >>> G = nx.read_pajek(\"test.net\")\n\n    To create a Graph instead of a MultiGraph use\n\n    >>> G1 = nx.Graph(G)\n\n    References\n    ----------\n    See http://vlado.fmf.uni-lj.si/pub/networks/pajek/doc/draweps.htm\n    for format information.\n    \"\"\"\n    lines = (line.decode(encoding) for line in path)\n    return parse_pajek(lines)\n\n\ndef parse_pajek(lines):\n    \"\"\"Parse Pajek format graph from string or iterable.\n\n    Parameters\n    ----------\n    lines : string or iterable\n       Data in Pajek format.\n\n    Returns\n    -------\n    G : NetworkX graph\n\n    See Also\n    --------\n    read_pajek()\n\n    \"\"\"\n    import shlex\n    # multigraph=False\n    if isinstance(lines, str):\n        lines = iter(lines.split('\\n'))\n    lines = iter([line.rstrip('\\n') for line in lines])\n    G = nx.MultiDiGraph()  # are multiedges allowed in Pajek? assume yes\n    labels = []  # in the order of the file, needed for matrix\n    while lines:\n        try:\n            l = next(lines)\n        except:  # EOF\n            break\n        if l.lower().startswith(\"*network\"):\n            try:\n                label, name = l.split(None, 1)\n            except ValueError:\n                # Line was not of the form:  *network NAME\n                pass\n            else:\n                G.graph['name'] = name\n        elif l.lower().startswith(\"*vertices\"):\n            nodelabels = {}\n            l, nnodes = l.split()\n            for i in range(int(nnodes)):\n                l = next(lines)\n                try:\n                    splitline = [x.decode('utf-8') for x in\n                                 shlex.split(str(l).encode('utf-8'))]\n                except AttributeError:\n                    splitline = shlex.split(str(l))\n                id, label = splitline[0:2]\n                labels.append(label)\n                G.add_node(label)\n                nodelabels[id] = label\n                G.nodes[label]['id'] = id\n                try:\n                    x, y, shape = splitline[2:5]\n                    G.nodes[label].update({'x': float(x),\n                                           'y': float(y),\n                                           'shape': shape})\n                except:\n                    pass\n                extra_attr = zip(splitline[5::2], splitline[6::2])\n                G.nodes[label].update(extra_attr)\n        elif l.lower().startswith(\"*edges\") or l.lower().startswith(\"*arcs\"):\n            if l.lower().startswith(\"*edge\"):\n                # switch from multidigraph to multigraph\n                G = nx.MultiGraph(G)\n            if l.lower().startswith(\"*arcs\"):\n                # switch to directed with multiple arcs for each existing edge\n                G = G.to_directed()\n            for l in lines:\n                try:\n                    splitline = [x.decode('utf-8') for x in\n                                 shlex.split(str(l).encode('utf-8'))]\n                except AttributeError:\n                    splitline = shlex.split(str(l))\n\n                if len(splitline) < 2:\n                    continue\n                ui, vi = splitline[0:2]\n                u = nodelabels.get(ui, ui)\n                v = nodelabels.get(vi, vi)\n                # parse the data attached to this edge and put in a dictionary\n                edge_data = {}\n                try:\n                    # there should always be a single value on the edge?\n                    w = splitline[2:3]\n                    edge_data.update({'weight': float(w[0])})\n                except:\n                    pass\n                    # if there isn't, just assign a 1\n#                    edge_data.update({'value':1})\n                extra_attr = zip(splitline[3::2], splitline[4::2])\n                edge_data.update(extra_attr)\n                # if G.has_edge(u,v):\n                #     multigraph=True\n                G.add_edge(u, v, **edge_data)\n        elif l.lower().startswith(\"*matrix\"):\n            G = nx.DiGraph(G)\n            adj_list = ((labels[row], labels[col], {'weight': int(data)})\n                        for (row, line) in enumerate(lines)\n                        for (col, data) in enumerate(line.split())\n                        if int(data) != 0)\n            G.add_edges_from(adj_list)\n\n    return G\n\n\ndef make_qstr(t):\n    \"\"\"Returns the string representation of t.\n    Add outer double-quotes if the string has a space.\n    \"\"\"\n    if not isinstance(t, str):\n        t = str(t)\n    if \" \" in t:\n        t = f'\"{t}\"'\n    return t\n", "path": "networkx/readwrite/pajek.py"}]}