2

Is there a way to convert any variable name to a string that would be a valid filename (under Linux and Windows)?

Specifically, I would like Greek letters to be replaced by a spelled out form or just the corresponding English letter and any illegal characters to be removed. But something more general would be nice for future use (Something that also works for for instance:\[GothicCapitalD].

I'm thinking the basic operation needed would be to convert symbols back to their alias or full name and then remove all remaining illegal characters.

A related question was asked here Convert String to clean file-name. This tell us how to remove specific illegal characters, but doesn't offer a general solution.

The best I could come up with myself:

tofilename = 
 StringReplace[
   ToString[FullForm[#]], {"\\" -> "", "[" -> "", "]" -> ""}] &

I'd prefer to convert to the alias or a shorter name because this gets quite ugly, but I guess that might not be possible.

Has anyone got a better Idea?


I didn't add a minimal example because I thought I'd described the minimal example in words and the fact that I can't show Greek letters here makes an explicit example slightly odd. Anyway here it is: For a variable with the following name (but with the Greek letters written as their symbols, I can't format that here correctly right?)

test\[CapitalDelta]\[Delta]

I would (ideally) like to convert this to either testDeltadelta or testDd (the last one has the convenience of creating simple names but the disadvantage that we are much more likely to run into overlapping mappings).

Applying the function I came up with we get halfway there:

tofilename@test\[CapitalDelta]\[Delta]

Output:

testCapitalDeltaDelta

The goal would be to create a quick function that I can put after defining a variable //export that exports it to a file according to a standardized format. There are of course alternative ways to do this, about which I'm also happy to hear (but the real goal is of course also to satisfy my curiosity).


Also, no this question isn't answered in Convert String to clean file-name. It is related though, which is why I already referred to it in my question and explained the difference. I'm sorry if the explanation wasn't clear enough.

Kvothe
  • 4,419
  • 9
  • 28
  • This seems like an unusual thing to do. I'm curious what you're trying to accomplish---there may be a better way. – Pillsy Apr 25 '17 at 18:02
  • please provide a minimal example. also you can use the following: StringReplace[ToString[FullForm[#]], "\\" | "[" | "]" -> ""]& – Ali Hashmi Apr 25 '17 at 19:03

0 Answers0