Skip to main content
 首页 » 编程设计

python之返回一个字典,其中不同的单词作为键,它在文本中的出现位置作为值

2025年05月04日16kerrycode

假设我有一个字符串

"I say what I mean. I mean what I say. i do." 

我正在尝试编写一个函数,它将返回一个如下所示的字典:

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

它所做的是,它只将每个字符作为键放入字典中一次,并显示它出现在哪个句子中作为与该键相关的值。例如,单词“mean”出现在第一个 [0] 和第二个 1 中。句子。另一方面,“做”这个词只出现在第三个句子中,因此:

'do':[2] 

在输出中。

这是我在更改我能想到的所有内容以获取要与每个键配对的值列表之后想出的代码。

def wordsD(text): 
#split each sentences at '.' 
myList = text.lower().split('.') 
#declare empty dictionary for the counter 
myDict = {} 
counterList = [] 
for sentence in myList: 
    words = sentence.split() 
    for 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) 
 
 
return myDict 
 
 
text=('I say what I mean. I mean what I say. i do.') 
print(wordsD(text)) 

这是我得到的输出:

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

但现在我不确定是我理解错了问题还是我的代码中遗漏了什么。任何帮助都会很棒!即使是指向正确方向的指针也会帮助我,因为即使我尝试为这个问题编写伪代码,我也会一头雾水。谢谢!

我看了Counting vowels和 Turning a text file with words and their positions into a sentence但我仍然无法弄清楚如何将列表作为每个键的值。

请您参考如下方法:

这绝对能帮到你。

string = "I say what I mean. I mean what I say. i do." 
 
DICT = {} 
 
LIST  =  string.split('.') 
 
WORDS = list(set(string.lower().replace('.',"").split())) 
 
LIST = [set((x.lower()).split()) for x in LIST] 
 
for i in range(len(LIST)): 
    for item in WORDS: 
        if item in LIST[i]: 
            DICT.setdefault(item, []).append(i) 
print(DICT) 

输出

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