-2

我不确定如何在python 3.xx中完成这个问题定义一个函数wordsD,它接受一个参数:1.文本,一个字符串文本包含单词由空格分隔并以句点结尾的句子。该函数返回一个 word/sentenceList 对的字典,其中 word 是文本中每个不同的词,而 sentenceList 是该词出现的句子索引列表。注意:您的代码对大小写不敏感,例如如果 text='I say我的意思是说。我的意思是我所说的。我愿意。" 函数返回 {'i":[0,1,2],'say':[0,1],'what':[0,1],'mean':[0,1],'做':[2]}

4

2 回答 2

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])}
于 2013-06-24T04:29:19.587 回答
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]}

如果您甚至不允许使用 enumerate

>>> 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]}
于 2013-06-24T04:37:55.487 回答