Skip to content

Instantly share code, notes, and snippets.

@ctufts
Last active November 7, 2015 22:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ctufts/20421d339f840230247a to your computer and use it in GitHub Desktop.
Save ctufts/20421d339f840230247a to your computer and use it in GitHub Desktop.
Find 'value' in a list of tokens and replace them with the 'key' of a dictionary. The dictionary can have multiple values per key. Example use: replacing multiple nick names with one common name.
s = ['c' ,'is', 'equal', 'to', 'b']
print(s)
# output >> ['c', 'is', 'equal', 'to', 'b']
# dictionary of names:values
d = {'joe':['a', 'b'], 'tom':['c', 'd']}
# replace any values from the dict with the key value
for i in range(0, len(s)):
for key,value in d.items():
for v in value:
s[i] = re.sub(r"\b%s\b" % v, key, s[i])
print(s)
# output >> ['tom', 'is', 'equal', 'to', 'joe']
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment