Update: An updated, more functional and more robust version of this palette is now available on GitHub. It is compatible with Mathematica 10.0 or later.
Have you ever wanted to quickly import some tabular data for quick-and-dirty analysis, either from the web, rich text document, part of a spreadsheet, etc., but then gave up because it seemed too much trouble? This is something I want to do quite frequently, so I wrote a small utility palette for directly pasting tables into Mathematica. To create the palette, just evaluate this code:
CreatePalette@Column@{Button["TSV",
Module[{data, strip},
data = NotebookGet[ClipboardNotebook[]][[1, 1, 1]];
strip[s_String] :=
StringReplace[s, RegularExpression["^\\s*(.*?)\\s*$"] -> "$1"];
strip[e_] := e;
If[Head[data] === String,
NotebookWrite[InputNotebook[],
ToBoxes@Map[strip, ImportString[data, "TSV"], {2}]]
]
]
],
Button["CSV",
Module[{data, strip},
data = NotebookGet[ClipboardNotebook[]][[1, 1, 1]];
strip[s_String] :=
StringReplace[s, RegularExpression["^\\s*(.*?)\\s*$"] -> "$1"];
strip[e_] := e;
If[Head[data] === String,
NotebookWrite[InputNotebook[],
ToBoxes@Map[strip, ImportString[data, "CSV"], {2}]]
]
]
],
Button["Table",
Module[{data},
data = NotebookGet[ClipboardNotebook[]][[1, 1, 1]];
If[Head[data] === String,
NotebookWrite[InputNotebook[],
ToBoxes@ImportString[data, "Table"]]
]
]
]}
There are three buttons, for handling three different types of tabular data: tab-separated (TSV), comma-separated (CSV), and generic whitespace separated (Table), corresponding to the input formats of the same names.
When you close Mathematica, the palette will be gone. If you decide to keep it permanently, choose Palette -> Install Palette from the menu, then select the palette notebook as the “Source”.
It’s particularly convenient to use this palette in conjunction with Firefox. Firefox has a little know feature: it is possible to select rectangular portions of tables while holding down the Control (or Command) keys. Try it e.g. with some tables on Wikipedia:
Then press Command-C to copy, place the input cursor inside a Mathematica notebook and press the TSV button on the palette. Firefox will copy the table as tab-separated data. This is very useful: not treating all whitespace as separators ensures that entires such as “Hong Kong” or “Gaza Strip” stay as single entries and don’t get broken into separate words. Here’s the result in Mathematica:
Note: I originally wrote this code for Mathematica 6, when there still weren’t any officially supported functions to handle the clipboard. In recent versions there are better ways to achieve the same thing. Nevertheless I decided to keep the original code here. It works well and it might prove of use for someone who still uses old versions of Mathematica.
Comments !