def replace_in_file()

in scripts/gen_api_doc.py [0:0]


def replace_in_file(fname, replacements):
    "replace content in file"
    cprint('|-Patching %s' % fname, 'cyan')
    content = open(fname).read()
    os.unlink(fname)

    for rep in replacements:
        content = re.sub(rep[0], rep[1], content, flags=re.MULTILINE)

    # fix the header manually as there is no easy regex
    head = []
    body = []
    is_head = True
    for l in content.split('\n'):

        # fix h3 first
        l = l.replace("><code>", '>')
        l = l.replace("</code></h3>", '</h3>')

        # stop when getting subsection
        if len(l) and l[0] == "##" or "<!-- Placeholder" in l:
            is_head = False

        l = l.replace("<code>", "```python\n")
        l = l.replace('</code>', "```\n")
        l = l.replace('</pre>', '')
        l = l.replace("&#x27;", '')

        if is_head:

            # remove remaining html
            if "on GitHub" in l:
                continue

            if "<" in l:
                continue
            head.append(l)
        else:
            if '<pre' in l:
                continue
            l = re.sub('`([^`]+)`', '<b>\g<1></b>', l)
            l = re.sub('{([^`]+)}', '<i>\g<1></i>', l)

            body.append(l)

    #print(head)

    content = "\n".join(head)
    content += "\n".join(body)

    with open(fname, 'w+') as f:
        f.write(content)