Skip to content

Instantly share code, notes, and snippets.

@mtholder
Last active August 29, 2015 14:16
Show Gist options
  • Select an option

  • Save mtholder/8e8220d2ec1609548a86 to your computer and use it in GitHub Desktop.

Select an option

Save mtholder/8e8220d2ec1609548a86 to your computer and use it in GitHub Desktop.
indent a fragment of a newick to make it easier to grab a subtree - does not correctly parse labels (so quoted parens and commas cause problems)
#!/usr/bin/env python
from StringIO import StringIO
import sys
out = sys.stdout
def get_indented(x, indent):
start_indent = indent
written_something = False
out = StringIO()
for letter in x:
if letter == '(':
if written_something and not prev_comma:
out.write('\n' + ' '*indent)
out.write('(')
indent += 1
elif letter == ')':
indent -= 1
if indent < 0:
return get_indented(x, start_indent + 1)
out.write('\n' + ' '*indent + ')')
elif letter == ',':
out.write(',\n' + ' '*indent)
else:
out.write(letter)
written_something = True
prev_comma = letter == ','
out.write('\n')
return out.getvalue()
if len(sys.argv) == 1:
for line in sys.stdin:
ls = line.strip()
out.write(get_indented(ls, 0))
else:
for arg in sys.argv[1:]:
out.write(get_indented(arg, 0))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment