我有一个文件random.txt
,我需要从中读取每个单词,并在字典中索引位置和字母。例如,它将如下所示:{(3,'m'):'example'}
。每次有一个单词在同一位置上有相同的索引字母时,它只会将该单词添加到字典的值中,因此它应该是{(3,'m'):'example','salmon'}
而不是单独打印每个单词。将字典添加到字典
这就是我所拥有的,每次它只是使它自己的值每次都不会将该单词添加到该键的值中。
def fill_completions(c_dict, fileObj):
import string
punc = string.punctuation
for line in fileObj:
line = line.strip()
word_list = line.split() #removes white space and creates a list
for word in word_list:
word = word.lower()
word = word.strip(punc) #makes lowercase and gets rid of punctuation
for position,letter in enumerate(word):
"position: {} letter: {}".format(position,letter)
my_tuple = (position,letter)
if word in my_tuple:
c_dict[my_tuple] += word
else:
c_dict[my_tuple] = word
print(c_dict)