Created
August 31, 2017 11:42
-
-
Save eHammarstrom/6e8984578685264acccab565aa5af778 to your computer and use it in GitHub Desktop.
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
#!/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