Better way to copy demo code from docs.python.org

I read a lot of code in Python docs. So there comes so much demo code to run on my own way with modifications. So I have to copy those demo, but its format is like:

>>> transposed = []
>>> for i in range(4):
... # the following 3 lines implement the nested listcomp
... transposed_row = []
... for row in matrix:
... transposed_row.append(row[i])
... transposed.append(transposed_row)

Needs to be turned to:

transposed = []
for i in range(4):
# the following 3 lines implement the nested listcomp
transposed_row = []
for row in matrix:
transposed_row.append(row[i])
transposed.append(transposed_row)

This leads to a fix of removing “>>>” and “…” and also indentations and it takes time.

So I decided to create a Chrome extension to help me out. This is quite simple, that when I copy the demo code, it removes those redundancies and be ready to be run.

I use this regex to catch it:

/^>>> |^... |^...$/gm

The rest is so simple, just several minutes for a simple extension.

document.addEventListener('copy', function(e) {
    var selectedText = window.getSelection().toString();

    if (~selectedText.indexOf('>>>')) {
        var fixedCode = selectedText.replace(/^>>> |^... |^...$/gm, '');
        e.clipboardData.setData('text/plain', fixedCode);
        e.preventDefault();
    }
});

Source code: https://github.com/ducfilan/Copy-Python-docs-code-extension

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s