2

I want to convert a google docs document to a text file preserving indentation. When I copy and paste, or export indentation seems to be lost.

Work around

I'm looking into exporting to html and then getting the indentation from this - but this feels a bit silly. It looks like css classes in the html export indicate indentation. This probably isn't at all stable though.

<p class="c1 c3 c2">

This snippet works for my use case:

#!/usr/bin/env python3

import argparse
import re

import lxml.etree
from lxml.etree import tostring

PARSER = argparse.ArgumentParser()
PARSER.add_argument("html")
args = PARSER.parse_args()

with open(args.html) as stream:
    t = lxml.etree.HTML(stream.read())

for p in t.xpath("//p"):
    classes = p.attrib["class"].split()
    (text,) = p.xpath("./descendant-or-self::*/text()")
    indent = 0
    for x in classes:
        class_indent = int(re.match(r"c(\d+)", x).group(1))
        indent = max(indent, class_indent)
    print((indent - 1) * "\t" + text)

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.