首页 > 解决方案 > 输出字典中的单词位置

问题描述

我有一个文本文件要分析,要求是输出字典,key是单词,value是单词位置(有些单词在文本中出现了好几次,所以单词有多个位置作为值词典 )。比如任何地方:[1,4,6,8,10]。但是我的输出只出现在单词的一个位置,比如anywhere [1]:. 我在这里真的很困惑,这是我的代码和输出。另外,我只能使用内置函数,我不能导入任何其他函数。

file_name = input('Enter the file name: ')
words_data = open(file_name, 'r')
words_list = []
new_word_list = []
word_index= []
dictionary = {}
for line in words_data:
    words = line.split()
    for word in words:
        words_list.append(word.lower())
for word_p in words_list:
    word_np = word_p.strip('?.,;:!-')
    new_word_list.append(word_np)
    if word_np in new_word_list:
        word_index.append(new_word_list.index(word_np))

dictionary = {}

for final_word in new_word_list:
    word_position = dictionary.get(final_word,None)
    if word_position == None:
            dictionary[final_word] = new_word_list.index(final_word)

print(dictionary)
#Outputs#
Enter the file name: greenEggsham.txt
{'rain': 420, 'car': 194, 'thank': 778, 'try': 635, 'eggs': 20, 'could': 190, 'or': 42, 'them': 27, 'there': 43, 'fox': 143, 'the': 393, 'see': 216, 'good': 719, 'be': 239, 'train': 301, 'boat': 518, 'would': 37, 'that': 6, 'let': 237, 'so': 632, 'do': 11, 'i': 0, 'with': 83, 'will': 215, 'like': 13, 'ham': 22, 'you': 17, 'green': 19, 'am': 1, 'are': 201, 'goat': 503, 'they': 200, 'here': 41, 'me': 238, 'and': 21, 'eat': 132, 'in': 76, 'house': 78, 'if': 650, 'on': 312, 'say': 391, 'sam-i-am': 7, 'dark': 394, 'not': 12, 'anywhere': 57, 'box': 136, 'sam': 2, 'may': 211, 'a': 77, 'spam': 384, 'tree': 223, 'mouse': 85}

标签: pythondictionary

解决方案


每次访问密钥时,您都会覆盖字典值。正如 shaik 提到的,使用列表作为字典值并每次都附加到列表中。

例如:

for final_word in new_word_list:
    word_position = dictionary.get(final_word,None)
    if word_position == None:
            if final_word in dictionary:
                dictionary[final_word].append(new_word_list.index(final_word))
            else:
                dictionary[final_word] = [new_word_list.index(final_word)]

推荐阅读