Text Utilities

json_sorter

Take a json file, sort the keys and insert 4 spaces for indents.

json sorter

One Line Solution

>>> sorted((json.loads(open('settings.json').read()).items()), key=operator.getitemattr)

You definitely shouldn’t implement it as a one liner, as you can clearly see,; however 5 functions and a handful of instantiated classes and debugging, and we’re somehow barely closer to done.

The functions for reading and writing files could be refactored and used over the entire package.

The logger should be set up that way.

This code is going to easily clear 100 lines when a JSON encoded object shouldn’t take more than a few lines to deserialize and work with.

This’ll serve as a good template for testing out tools to build a simple script with.

The problem is already solved. Let’s see what we can’t squeeze out of our tools along the way.

Interestingly enough, this display of excessiveness started as a simple quick fix.

Originally, this module was used to fix my ../.vscode/settings.json from VSCode.


pyutil.json_sorter._parse_arguments()[source]

Parse arguments given by the user.

This implementation still, somehow isn’t done. An option for inplace modifications needs to be added.

Unfortunately this will be mutually exclusive to the output file option. So we’ll need to work on learning argparse.mutually_exclusive_groups.

Returns

args – Arguments provided by the user and handled by argparse.

Return type

argparse.NameSpace()

pyutil.json_sorter.convert_to_yaml(file_obj)[source]

Convert a json to YAML.

Parameters

file_obj (str) – The file to read in

Returns

yaml_object – Converted PyYAML text.

Return type

str

pyutil.json_sorter.main()[source]

Handles user args, sets up logging and calls other functions.

pyutil.json_sorter.sort_json(file_obj)[source]

Read in a json object, sort it and write it back to a new file.

By writing to a new file, the user is allowed the opportunity to inspect the file and ensure that the desired results have been achieved.

Parameters

file_obj (str) – The file to read in

Returns

json_text – Correctly formmated json text.

Return type

str

pyutil.json_sorter.text_writer(plaintext, output_file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]

Write the previously inputted text to a file.

This function could easily be utilized over the whole package though.

Parameters
  • plaintext (str) – The file to read in

  • output_file (str) – Text file to write formatted json to. It will only write to the file if the filename currently doesn’t exist.

wrap

Wrap text similarly to textwrap.dedent() but with multiple paragraphs.

Allow the user to input any parameters that are accepted by textwrap.TextWrapper()

Utilizes prompt_toolkit.print_formatted_text to easily display prettified text.

Just dropped string2lines down there thanks to docutils and the docutils.state_machine.

class pyutil.wrap.ZimText(text=None, width=80, break_long_words=False, break_on_hyphens=False, **kwargs)[source]

Bases: textwrap.TextWrapper

Subclass textwrap.TextWrapper().

Primarily want to modify initialized arguments. Not entirely looking to reimplement the text formatting methods, both private and public.

Now the publicly available methods from TextWrapper.:

>>> from textwrap import TextWrapper
>>> dir(TextWrapper)
['_fix_sentence_endings',
'_handle_long_word',
'_munge_whitespace',
'_split',
'_split_chunks',
'_wrap_chunks',
'fill',
'sentence_end_re',
'unicode_whitespace_trans',
'uspace',
'wordsep_re',
'wordsep_simple_re',
'wrap',
'x']
string2lines(self, convert_whitespace=True)[source]
wrap_paragraphs(self)[source]

Wrap multiple paragraphs to fit a specified width.

This is equivalent to textwrap.wrap(), but with support for multiple paragraphs, as separated by empty lines.

Parameters
Returns

wrapped_text – list of complete paragraphs, wrapped to fill ncols columns.

Return type

list of str

Examples

>>> from wrap import ZimText
>>> wrapper = ZimText()
>>> f = open('unix-ide-editing.txt')
>>> text = f.read()
>>> wrapped = wrapper.wrap(text)
>>> with open('unix-ide-editing.txt', 'wt') as f:
...     f.write(text)