2013-03-18 86 views
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) 

回答

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'] 
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)