我不确定如何在python 3.x.x中完成此问题 定义一个带有一个参数的函数单词D: 1.文字,一个字符串 文本包含用空格分隔的单词的句子 并以句号结束。 该函数返回一个字典 单词/ sentenceList对,其中单词各自不同 文本中的单词和sentenceList是列表 这个词出现的句子索引。 注意:您的代码对大小写字母不敏感 例如 if text ='我说出我的意思。我是说我说的。我做。” 功能返回 {“我”:[0,1,2], '说':[0,1], '什么':[0,1], '平均':[0,1], '做':[2] }
答案 0 :(得分:2)
您可以在此处使用collections.defaultdict
:
>>> from collections import defaultdict
>>> text= "I say what I mean. I mean what I say. i do."
# convert the text to lower-case and split at `'.'` to get the sentences.
>>> sentences = text.lower().split('.')
>>> dic = defaultdict(set) #sets contain only unique iteme
for i,sen in enumerate(sentences): #use enumerate to get the sentence as well as index
for word in sen.split(): #split the sentence at white-spaces to get words
dic[word].add(i)
>>> dic
defaultdict(<type 'set'>,
{'i': set([0, 1, 2]),
'do': set([2]),
'say': set([0, 1]),
'what': set([0, 1]),
'mean': set([0, 1])})
使用普通字典:
>>> dic = {}
for i,sen in enumerate(sentences):
for word in sen.split():
dic.setdefault(word,set()).add(i)
...
>>> dic
{'i': set([0, 1, 2]),
'do': set([2]),
'say': set([0, 1]),
'what': set([0, 1]),
'mean': set([0, 1])}
没有enumerate
:
>>> dic = {}
>>> index = 0
for sen in sentences:
for word in sen.split():
dic.setdefault(word,set()).add(index)
index += 1
...
>>> dic
{'i': set([0, 1, 2]), 'do': set([2]), 'say': set([0, 1]), 'what': set([0, 1]), 'mean': set([0, 1])}
答案 1 :(得分:0)
由于某些原因,人们经常会问如何在没有 defaultdict
的情况下执行此操作>>> text= "I say what I mean. I mean what I say. i do."
>>> sentences = text.lower().split('.')
>>> dic = {}
>>> for i, sen in enumerate(sentences):
... for word in sen.split():
... if word not in dic: # you just need these
... dic[word] = set() # two extra lines
... dic[word].add(i)
...
>>> dic
{'i': set([0, 1, 2]), 'do': set([2]), 'say': set([0, 1]), 'what': set([0, 1]), 'mean': set([0, 1])}
如果你真的想要列表,这里有一个修改
>>> text= "I say what I mean. I mean what I say. i do."
>>> sentences = text.lower().split('.')
>>> dic = {}
>>> for i, sen in enumerate(sentences):
... for word in sen.split():
... if word not in dic:
... dic[word] = [i]
... elif dic[word][-1] != i: # this prevents duplicate entries
... dic[word].append(i)
...
>>> dic
{'i': [0, 1, 2], 'do': [2], 'say': [0, 1], 'what': [0, 1], 'mean': [0, 1]}
如果您甚至不允许使用枚举
>>> text= "I say what I mean. I mean what I say. i do."
>>> sentences = text.lower().split('.')
>>> dic = {}
>>> i = -1
>>> for sen in sentences:
... i += 1
... for word in sen.split():
... if word not in dic:
... dic[word] = [i]
... elif dic[word][-1] != i: # this prevents duplicate entries
... dic[word].append(i)
...
>>> dic
{'i': [0, 1, 2], 'do': [2], 'say': [0, 1], 'what': [0, 1], 'mean': [0, 1]}