Skip to content

Instantly share code, notes, and snippets.

@paultopia
Created May 26, 2016 00:13
Show Gist options
  • Select an option

  • Save paultopia/c6b3d2c440d6f17f56c314130e58b5fb to your computer and use it in GitHub Desktop.

Select an option

Save paultopia/c6b3d2c440d6f17f56c314130e58b5fb to your computer and use it in GitHub Desktop.
add labels for regex to dict of data
# Common data cleaning pattern: you need to find regex matches in some block of text, stored w/ labels in a
# dictionary (i.e., from json), extract those matches, and store them as an additional labels.
# here's a quick and dirty utility function to do so. can then be used in loop or listcomp over entire dataset
import re
from collections import Counter
def pattern_extractor(instance, pattern, textlabel, newlabel):
found = re.findall(pattern, instance[textlabel])
if found:
if isinstance(found[0], (list, tuple)):
matches = [filter(None, x)[0] for x in found]
else:
matches = filter(None, found)
instance[newlabel] = sorted(Counter(matches).most_common())
return instance
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment