Last active
April 2, 2016 04:12
-
-
Save joefusaro/1cba7ba5076331c62767d805fed7943a to your computer and use it in GitHub Desktop.
Take a text string and a list of dictionary objects; replaces each value in a string with the corresponding key.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class TextLabeler(): | |
"""Takes a text string and a list of dictionary objects; replaces each | |
occurence of a value in a string with the corresponding key. For example: | |
>>> string = "Let's take a trip to Paris next January" | |
>>> lod = [{'city':'Paris'}, {'month':'January'}] | |
>>> processed = TextLabeler(string, lod) | |
>>> processed.text | |
>>> Let's take a trip to [[ city ]] next [[ month ]] | |
lod: abbreviated for `List of Dicts`; expects a list of dict objects | |
""" | |
def __init__(self, text, lod): | |
self.text = text | |
self.iterate(lod) | |
def replace_kv(self, _dict): | |
"""Replace any occurrence of a value with the key""" | |
for key, value in _dict.iteritems(): | |
label = """[[ {0} ]]""".format(key) | |
self.text = self.text.replace(value, label) | |
return self.text | |
def iterate(self, lod): | |
"""Iterate over each dict object in a given list of dicts, `lod` """ | |
for _dict in lod: | |
self.text = self.replace_kv(_dict) | |
return self.text |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment