Continuing from my previous question, this issue is an extension of it.
This issue is somewhat similar to how-do-i-make-a-string-literal-without-having-to-escape-backslashes? but not entirely the same, since I'm thinking of first storing a string in a variable and then declaring that it should be preserved as-is without escaping any escape characters encountered. I just give an example about graph6 strings from graph theory.
s = "ihChWC@?gE_@?@?A_@g?@??C??j?@l??E??Ao??\???m??@I??DF??E`O??GM??@?\
g??S\@o?@g@O??G?w??C?I??D?@o?@g?D???_?M??@??I??D??FK?E_?@Q??G??N??@???\
CPCOaG\a??"
I use the codes from the above link, but it still does not work.
$PreRead = (# /.
RowBox@{"RawString", "[", str_String, "]"} |
RowBox@{"RawString", "@", str_String} |
RowBox@{str_String, "//", "RawString"} :>
RowBox@{"StringTrim", "[", ToString@InputForm@str, ",",
"\"\\\"\"", "]"}) &;
s1 = RawString@s
ImportString[s1, "Graph6"]
The code above seems to require the string immediately following RawString
, rather than storing the string in a variable. What should I do in this case?
s1 = RawString@
"ihChWC@?gE_@?@?A_@g?@??C??j?@l??E??Ao??\???m??@I??DF??E`O??GM??@?\
g??S\@o?@g@O??G?w??C?I??D?@o?@g?D???_?M??@??I??D??FK?E_?@Q??G??N??@???\
CPCOaG\a??"
ImportString[s1, "Graph6"]
I tried to replace the character \
with \\
, but it still failed.
s = "ihChWC@?gE_@?@?A_@g?@??C??j?@l??E??Ao??\???m??@I??DF??E`O??GM??@?\
g??S\@o?@g@O??G?w??C?I??D?@o?@g?D???_?M??@??I??D??FK?E_?@Q??G??N??@???\
CPCOaG\a??";
s1 = StringReplace[s, "\\" -> "\\\\"];
ImportString[s1, "Graph6"]
Import::fmterr: Cannot import data as Graph6 format.
I know that in Python, one way to do it is as follows:
import networkx as nx
escape_dict={'\a':r'\a',
'\b':r'\b',
'\c':r'\c',
'\f':r'\f',
'\n':r'\n',
'\r':r'\r',
'\t':r'\t',
'\v':r'\v',
'\'':r'\'',
'\"':r'\"'}
def raw(text):
"""Returns a raw string representation of text"""
new_string=''
for char in text:
try:
new_string += escape_dict[char]
except KeyError:
new_string += char
return new_string
line = 'ihChWC@?gE_@?@?A_@g?@??C??j?@l??E??Ao??\???m??@I??DF??E`O??GM??@?g??S\@o?@g@O??G?w??C?I??D?@o?@g?D???_?M??@??I??D??FK?E_?@Q??G??N??@???CPCOaG\a??'
line=raw(line)
G = nx.from_graph6_bytes(line.encode())
print(G)
See also how-to-prevent-automatic-escaping-of-special-characters-in-python.
Can Mathematica handle it in a similar way?