项目作者: dankilman

项目描述 :
Scratchpad for tabular data transformations
高级语言: Python
项目地址: git://github.com/dankilman/textomatic.git
创建时间: 2020-10-05T19:30:27Z
项目社区:https://github.com/dankilman/textomatic

开源协议:MIT License

下载


textomatic

Scratchpad for tabular data transformations

Given input of some tabular data (AKA INPUT),
and a command (AKA COMMAND), transform that input
into some other output (AKA OUTPUT).

Screencast Demo

Installation

```shell script
pip install textomatic

  1. At the moment, Python 3.8 or greater is required.
  2. ## Running
  3. Start it by running
  4. ```shell script
  5. $ tm

The above will start textomatic with a blank slate.

You can load a file by passing it as the first argument:
```shell script
$ tm

  1. You can also pipe content from stdin:
  2. ```shell script
  3. $ ls | tm

To see what arguments/options are available, run:

  1. $ tm --help

When textomatic is running, type F1 to see available keyboard shortcuts.

To exit textomatic use CTRL-C to exit without any output or CTRL-O to print
current OUTPUT into standard out.

Use CTRL-P to put the current OUTPUT in the system clipboard.

Examples

Parsing ps aux output

Pipeing content from shell using ps aux | tm and transforming it into json lines where
each line containes the USER and PID columns with lower cased keys.
PID is casted into an integer.

COMMAND:

  • h says INPUT includes a header
  • i:sh says the INPUT should be parsed like shell output
  • s:{user:USER,pid:PID} specifies the output structure
  • o:jl specifies the output format to be json lines
  • t:PID:i specifies the PID column shouldd ge parsed as integer
    1. INPUT OUTPUT
    2. USER PID %CPU %MEM │{"user": "dan", "pid": 63507}
    3. dan 63507 6.3 0.4 6178│{"user": "_windowserver", "pid": 250}
    4. _windowserver 250 4.4 0.3 12494│{"user": "dan", "pid": 54987}
    5. dan 54987 3.8 12.8 16080│{"user": "_hidd", "pid": 184}
    6. _hidd 184 2.0 0.0 5608
    7. vi-insert|COMMAND|live|in:sh|out:jl|delim:auto|header:true
    8. > h;i:sh;s:{user:USER,pid:PID};o:jl;t:PID:i

Pretty printing csv

COMMAND:

  • h says INPUT includes a header
  • o:t specifies the output format to be a pretty printed table
    1. INPUT OUTPUT
    2. Name,Age,City │╒═══════════╤═══════╤════════╕
    3. James Joe,34,NYC ││ Name Age City
    4. John Doe,25,London │╞═══════════╪═══════╪════════╡
    5. ││ James Joe 34 NYC
    6. │├───────────┼───────┼────────┤
    7. ││ John Doe 25 London
    8. │╘═══════════╧═══════╧════════╛
    9. vi-insert|COMMAND|live|in:c|out:t|delim:auto|header:true
    10. > h;o:t

Correcting bad input

COMMAND:

  • h says INPUT includes a header
  • t:Age:i/76/ provides a default value when the Age column cannot be parsed as integer
    1. INPUT OUTPUT
    2. Name,Age,City │[['James Joe', 34, 'NYC'],
    3. James Joe,34,NYC ['John Doe', 76, 'London'],
    4. John Doe,Not a number,London ['Jane Row', 24, 'Tel Aviv']]
    5. Jane Row,24,Tel Aviv
    6. vi-insert|COMMAND|live|in:c|out:l|delim:auto|header:true
    7. > h;t:Age:i/76/

Interactive jq

COMMAND:

  • r puts evaluation into raw mode where input is not assumed to be raw based
  • o:jq use the jq output and pass arguments to it wrapped with backticks.
    1. INPUT OUTPUT
    2. {"one": 1, "two": 2, "three": 3} │{"o":1,"t1":2,"t2":3}
    3. {"one": 1.0, "two": 2.0, "three": 3.0} │{"o":1,"t1":2,"t2":3}
    4. vi-insert|COMMAND|live|in:c|out:jq|delim:auto|header:false|raw:true
    5. > r;o:jq`{o: .one, t1: .two, t2: .three}`

Usage

textomatic is split into 3 parts:

  • INPUT: The input data that is to be transformed
  • OUTPUT: The result of applying the COMMAND on INPUT
  • COMMAND: The transformation logic using a succinct expression language described below

Use the Tab key to move between them.

INPUT and COMMAND are edited using vim bindings.

COMMAND Expression Language

COMMAND is composed of different parts separated by ;, e.g.

  1. > h;i:c;o:jl;s:[1,2]

The above will be explained in detail later on but for now we can see it has 4 parts:

  • h: specifies that the input csv has a header
  • i:c specifies that the input is in fact a csv
  • o:jl specified that the output should be in jsonlines format
  • s:[1,2] specifies that the output should only include the first and
    1. second columns from the input, in that order

To use a different expression separator, start the command with :<SEP>, e.g.

  1. > :|h|i:c

Expressions

The h expression (header)

The simplest expression. It is basically a flag denoting whether the input
includes headers. This is relevent for inputs like csv

The d expression (delimiter)

Used by the csv input. In most cases, the delimiter can be automatically
deduced. In cases where it cannot, use d, e.g. to set a , delimiter:

  1. > d:,

To specify delimiters that are not easy to input, start the delimiter with
\, the remaining part will then be parsed as a python literal
(wrapped in string), for example this will set the delimiter to the unicode
character (U+2500):

  1. > d:\u2500
The i expression (input)

Used to specify the input format. Currently these are the available inputs:

  • c (csv, this is the default. The delimiter musn’t be a , as the name may imply)
  • jl (jsonlines)
  • sh (shell, e.g. the output of ps aux)
  • jq (Using jq)
The o expression (output)

Used to specify the output format. Currently these are the available outputs:

  • l (python literal, this is the default)
  • j (json)
  • jl (jsonlines)
  • c (csv)
  • t (pretty printed table)
  • h (table html)
  • jq (Using jq)
The t expression (types)

For inputs with no clear types (e.g. csv/shell), all columns are initially assumed to
be strings. To modify types of different columns use t.

The types are:

  • s (string, the default)
  • f (float)
  • i (integer)
  • b (boolean, case insensitive true/yes/y/on/1 will be parsed as true)
  • j (json, will JSON parse the column)
  • l (literal, will parse a python literal using ast.literal_eval)

Using positional syntax:

  1. > t:i,i,b

In the above:

  • the first 2 columns will be parsed as integers
  • the third column will be parsed as boolean
  • the rest will be strings

Using indexed syntax:

  1. > t:1:i,3:f

In the above:

  • the first column will be parsed as integer
  • the third column will be parsed as float
  • the rest will be strings

Using named syntax:

  1. > t:col1:b,col4:i

In the above, assuming the input contains headers:

  • the column named col1 will be parsed as boolean
  • the column named col4 will be parsed as integer
  • the rest will be strings

Optional types:

If a certain value may be invalid, you can use ? to
mark it as optional, in this case, its value will be
converted to null when it is invalid:

  1. > t:col1:i?,col4:i?

Defaults:

If you want the specify a value different than null for invalid entries
use the following syntax:

  1. > t:col1:i/0/,col4:f/0.0/

The value between the /‘s will be evaluated as a python literal.

The s expression (structure)

The s expression is used to specify the structure of the OUTPUT.
Some of the options are catered to the python output but they will fallback
to a reasonable alternative for other outputs.

Simple transformations:

  • s:[] - Each row will be a list in OUTPUT
  • s:() - Each row will be a tuple in OUTPUT
  • s:{} - Each row will be an object in OUTPUT (assumes input has headers)
  • s:d() - Same as s:{}
  • s:s() - Each row will be as set in OUTPUT

Complex transformations:

  • s:[1,2,col6] - Each row will contain the first and second columns and a column
    1. named `col6`. Note that it is wrapped with `[]`. This only
    2. means the output row will be a list. You can just as well
    3. wrap it with `{}` to get objects e.g. `s:{1,2,col6}`.
    4. The different wrapping options are desribed in "Simple Transformations"
    5. of the previous section.
  • s:{first:1,second:2} - Each row will contain the first and second columns with
    1. The specified new headers (`first` and `second`)
  • s:[-2,-1] - Each row will contain the two last columns from INPUT
  • s:{1,second:2} - Column definitions can be mixed.

Nested transformations:

  • s:[{1,2},{3,4}] - Each row will contain two objects, the first object will
    1. contain the first and second columns, the second object
    2. will contain the third and fourth columns.

Nesting can be as complex as you wish and rules from previous sections
can be applied freely. As an overly complex example:

  1. > s:{k1:1,k2:{2,three},k3:[{four,5},d(-4,s7:seven)],eight,k4:(one, two, (four, five)),s:s(1,1,1)}

Fetching values of nested data:

  • s:[some_obj.key1.key2] - Each row will contain a single nested value from
    1. the `some_obj` column.
  • s:[some_obj.key1?.key2] - Same as above, but don’t fail if key1 doesn’t exist,
    1. instead, replace it with `null`.
  • s:[some_obj.key1?.key2/100/] - Same as above, but use 100 instead of null.
  • s:[some_obj.key1.key2/100/] - Default value without optional ? is equivalent to
    1. `s:[some_obj?.key1?.key2?/100/]`

A caveat of using // for default values is that the default value cannot
include /. This is mostly due to a very simple parser that is currently
implemented for the expression language.