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