Group Abstract Group Abstract

Message Boards Message Boards

1
|
4.9K Views
|
7 Replies
|
3 Total Likes
View groups...
Share
Share this post:

Take a string from Python

Hello. I have a set of strings in Python and want to send them to .txt files
But to do that in Python is a pain in the neck
So I want to take the strings from Python a send them to Mathematica,
that would make everything very easy.
Is there a way to do this?
Send the string from Python to Mathematica.
Or retrieve the Python strings from Mathematica?

Any help is very appreciated

7 Replies

Connecting to Python is quick and easy in current versions of Wolfram Language. Here is a simple example that shuttles strings back and forth between the two languages. First start a Python external session:

session = StartExternalSession["Python"]

Define a function in Python that does something with a string (reversing the characters):

reverse = ExternalFunction[session, "
def string_reverse(a):
    return a[::-1]
"]

Now you can call this Python function from Wolfram Language:

reverse["Hello, world"]

Which will give you "dlrow ,olleH" as a result.

If you have specific follow-up questions, please let me know!

POSTED BY: Arnoud Buzing

Thank you for this. But next time do not lecture me for asking.

It doesn't help anybody, certainly not Mathematica

Posted 2 years ago
POSTED BY: Eric Rimbey

No, it is not so easy because the strings can have encoding issues. And besides, I simply want to know how to do it from Mathematica. The specific issues I am facing are easier to deal with from Mathematica.

If you want to display your knowledge, I am ok with this. But it does not help. So: withdrawing the pain in the neck clause, can this operation be done from Mathematica? And then how?

Hope my answer is not blocked this time.

Posted 2 years ago

I agree with Eric, writing an array of strings to a text file is trivial in Python not a "pain in the neck".

with open('file.txt', 'w') as f:
  for s in strings:
    f.write(f"{s}\n")

If that is your only use case then it seems like unnecessary complexity to involve WL in the process.

If your needs are more complex then take a look at this and this.

POSTED BY: Rohit Namjoshi

I am not asking for sympathy but for some kind of help. And this is not a Python but a Wolfram community

In Mathematica, things are simply easier. "Do want some sort of foreign function interface you can call from Python so that you can use Mathematica's Export function?"

Exactly, I simply coordinate all the things I do from Mathematica

Posted 2 years ago
POSTED BY: Eric Rimbey
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard