Skip to content

Instantly share code, notes, and snippets.

@eHammarstrom
Created August 31, 2017 11:42
Show Gist options
  • Save eHammarstrom/6e8984578685264acccab565aa5af778 to your computer and use it in GitHub Desktop.
Save eHammarstrom/6e8984578685264acccab565aa5af778 to your computer and use it in GitHub Desktop.
#!/bin/python
import re
from collections import defaultdict
words = defaultdict()
txt = "Hej mitt namn är hej och hej kanske och hej"
split = re.findall(r'\w+', txt.lower())
for i, w in enumerate(split): # enumerate gör så att vår iterator frår index och elment
if (words.get(w)): # Om ordet finns, appenda till listan
words[w].append(i)
else: # Om ordet inte finns, skapa en ny lista med ett element
words[w] = [i]
print(words) # defaultdict(None, {'hej': [0, 4, 6, 9], 'mitt': [1], 'namn': [2], 'är': [3], 'och': [5, 8], 'kanske': [7]})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment