python - return a dictionary with dictinct words as keys and it's position of occurence in the text as value -



python - return a dictionary with dictinct words as keys and it's position of occurence in the text as value -

say have string

"i mean. mean say. do."

i trying write function homecoming dictionary following:

{'i":[0,1,2],'say':[0,1],'what':[0,1],'mean':[0,1],'do':[2]}

what it's doing it's taking each character, once, dictionary key , displaying sentence appears in value relating key. eg, word "mean" appears in first [0] , sec 1 sentences. on other hand, word "do" appears in 3rd sentence, hence the:

'do':[2]

in output.

this code have come after changing can think of around list values pair each keys.

def wordsd(text): #split each sentences @ '.' mylist = text.lower().split('.') #declare empty dictionary counter mydict = {} counterlist = [] sentence in mylist: words = sentence.split() word in words: index = words.index(word) counterlist.append(index) if word not in mydict: mydict[word] = list() mydict[word].append(index) else: mydict[word]= list() mydict[word].append(index) homecoming mydict text=('i mean. mean say. do.') print(wordsd(text))

and output get:

{'mean': [1], 'what': [2], 'say': [4], 'i': [0], 'do': [1]}

but not sure if understood question wrong or missing in code. help great!! pointer in right direction help me out since coming blank when seek write psudo code problem. give thanks you!

i looked @ counting vowels , turning text file words , positions sentence still cant figure out how create list values each keys.

there 2 issues code. first, making new list in both if , else statements instead of appending existing list.

changing

else: mydict[word] = list() mydict[word].append(index)

to

else: mydict[word].append(index)

solves issue.

secondly, code tracking index within given sentence (ie word position) , not sentences nowadays in (which question indicates want). next code should prepare issue

def wordsd(text): mylist = text.lower().split('.') mydict = {} in range(len(mylist)): words = mylist[i].split() word in words: if word not in mydict: mydict[word] = [i] else: if not in mydict[word]: mydict[word].append(i) homecoming mydict

python loops python-3.x dictionary return

Comments

Popular posts from this blog

model view controller - MVC Rails Planning -

ruby on rails - Devise Logout Error in RoR -

html - Submenu setup with jquery and effect 'fold' -