{data dendrites} exploring data science with Python et al.

XKCD → Python → Julia

In Better Way to Read the News, a chapter from the online version of Everyday Python book, we find a function that implements the map from thix XKCD cartoon:

Original Python code:

def changeWord(word):
    if word in boring_news:
        idx = boring_news.index(word)
        return xkcd[idx]
    else:
        return word

I made a few changes to translate the function to Julia:

Out:

elf-lord
python

Translating the following function from Python to Julia was quite easy. It’s not just an exercise of looking up a difference in syntax, but also in using functional vs. object-oriented dot-notation.

Python:

article = '''Senator johnson was caught stealing a smartphone on election
night.  witnesses say that he allegedly took the smartphone from a kindly
old lady while she was washing her electric car. republican and democrat
congressional leaders have vowed to hold hearings.  Senator johnson could
not be reached for comment.'''

def translateNews(article, boringWords, funWords):
    article = article.lower()
    for idx in range(len(boringWords)):
        article = article.replace(boringWords[idx],funWords[idx])
    return article

print(translateNews(article,boring_news,xkcd))

Julia:

Out:

elf-lord johnson was caught stealing a pokedex on eating contest night.
dudes I know say that he allegedly took the pokedex from a kindly old
lady while she was washing her atomic cat. orc and hobbit
river spirits have vowed to hold hearings.  elf-lord johnson could
not be reached for comment.
comments powered by Disqus