Edit text with a script in Leo

60 views
Skip to first unread message

Jeremy Chen

unread,
Mar 27, 2018, 6:02:59 AM3/27/18
to leo-editor
Hi,

I'm a newbie. I read the tutorials a few times but I still can't figure out how to do this.

Let say I have a text file like this:

# bug fix for display formats to avoid run time errors
pandas
.set_option('display.float_format', lambda x:'%.2f'%x)

data
= pandas.read_csv('gapminder.csv')

# convert to numeric format
data
['internetuserate'] = pandas.to_numeric(data['internetuserate'], errors='coerce')
data
['urbanrate'] = pandas.to_numeric(data['urbanrate'], errors='coerce')
data
['femaleemployrate'] = pandas.to_numeric(data['femaleemployrate'], errors='coerce')


I need to substitute pandas with pd and numpy with np etc. (step 1)

Can I create a node and put the code into it? (step 2)

And then create another node where I write a script to automate a few repetitive substitutions? (step 3)

If so, how do I get step 3 and below going?
Can I read the body of the text node in to a variable and then just write python code to deal with it?
Then I have to output it to the console, a new node or file, right?

Any hint is appreciated. Thanks!

Edward K. Ream

unread,
Mar 27, 2018, 12:30:41 PM3/27/18
to leo-editor
On Tue, Mar 27, 2018 at 3:34 AM, Jeremy Chen <jere...@gmail.com> wrote:

Let say I have a text file like this:
​ [snip]

Leo scripts, including @button nodes, can do any kind of text formatting.​
 
 
I need to substitute pandas with pd and numpy with np etc. (step 1)

​Assuming p is the node containing your text, this will do what you want:​
 

​    p.b = p.b.replace('pandas', 'pd').replace('numpy', 'np')
 
Can I create a node and put the code into it? (step 2)

​Yes.  Something like this:

    p2 = c.p.insertAfter()
    p2.h = "My new node"

And then create another node where I write a script to automate a few repetitive substitutions? (step 3)

​Here is tested code.  Create @button substitute, with a body of:

# Make substitutions...
aList = [
    ('pandas', 'pd'),
    ('numpy', 'np'),
]
s = p.b
for pat1, pat2 in aList:
    s = s.replace(pat1, pat2)

# Create a new node, with the new text.
p2 = c.p.insertAfter()
p2.h = "Substitutions"
p2.b = s
c.selectPosition(p2)
c.redraw()

​Edward
Reply all
Reply to author
Forward
0 new messages