from bs4 import BeautifulSoup


def parse_sgm_file(sgm_data):
    """
    Returns a dictionary with titles + articles of an SGM file

    :param sgm_data: Data read from an SGM file
    :return: A dictionary mapping titles to article contents
    """

    soup = BeautifulSoup(sgm_data, features="html5lib")
    texts = soup.find_all('text')
    title_docs = {}
    for text in texts:
        title = text.findChild('title')

        # Title is non-existent for a few articles
        if title:
            # Use contents because the text has no name; always the last element
            title_docs[title.string.strip()] = text.contents[-1]

    return title_docs