0

我有一个文件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)
4

2 回答 2

1

目前您正在添加一个字符串,然后附加到该字符串。

您需要将一个元组作为您的值,然后添加到元组中。

>>> m = dict()
>>> m['key'] = 'Hello'
>>> m['key'] += 'World'
>>> print m['key']
HelloWorld
>>>
>>> m['key'] = ('Hello',)
>>> m['key'] += ('World',)
>>> print m['key']
('Hello', 'World')
>>> # Or, if you want the value as a list...
>>> m['key'] = ['Hello']
>>> m['key'].append('World')
>>> print m['key']
['Hello', 'World']
于 2013-03-18T23:42:37.823 回答
0

我认为您想将填充c_dict在最内层循环中的代码更改为以下内容:

            if my_tuple in c_dict:
                c_dict[my_tuple].add(word)
            else:
                c_dict[my_tuple] = set([word])

dict.setdefault()这是一个更简洁的等效版本:

            c_dict.setdefault(my_tuple, set()).add(word)
于 2013-03-18T23:56:48.573 回答