2014-10-17 77 views
1

我正在尝试创建一个列表字典,其中的关键字是anagrams,并且值(列表)包含所有可能出现的字符。从myFile中删除 n

所以我的字典应该包含这样的

{'aaelnprt': ['parental', 'paternal', 'prenatal'], ailrv': ['rival']} 

可能的话是一个.txt文件中。每个单词用换行符分隔的地方。示例

Sad 
Dad 
Fruit 
Pizza 

这导致了一个问题,当我尝试编码它。

with open ("word_list.txt") as myFile: 
    for word in myFile: 
     if word[0] == "v": ##Interested in only word starting with "v" 
      word_sorted = ''.join(sorted(word)) ##Get the anagram 
      for keys in list(dictonary.keys()): 
       if keys == word_sorted: ##Heres the problem, it doesn't get inside here as theres extra characters in <word_sorted> possible "\n" due to the linebreak of myfi 
        print(word_sorted) 
        dictonary[word_sorted].append(word) 

回答

1

如果在每一个词 “word_list.txt” 后面是 '\ n',那么你可以用切片摆脱这个词的最后一个字。

word_sorted = ''.join(sorted(word[:-1])) 

但是,如果在 “word_list.txt” 最后一个字是不是其次是 '\ n',那么你应该使用rstrip()

word_sorted = ''.join(sorted(word.rstrip())) 

slice方法会更有效,但对于这个应用程序,我怀疑你会发现其中的差别,所以你可能也只是起到安全&使用rstrip()

0

使用rstrip(),它消除了\n字符。

... 
... 
keys == word_sorted.rstrip() 
... 
+0

问:如果word_sorted有换行符,不应该只保留在字典的键值中。对不起,如果这是一个noob问题,但为什么要换行是特殊的? – Brad 2014-10-17 07:13:02

0

你应该尝试使用.rstrip()函数在你的代码,它会删除“\ n”

在这里,您可以检查它.rstrip()

0

条只能从删除角色字符串的开始或结束。

  • 使用rstrip()可以删除\ n字符

你也可以使用替代语法,用别的东西来代替换行。

STR2 = str.replace( “\ n”, “”)

0

所以,我在这里看到一些问题,如何进入字典,我看不到任务?显然你只给我们提供了一个片段,所以也许在别处。

当你可以使用in时,你也使用了一个循环(它更高效,确实是这样)。

with open ("word_list.txt") as myFile: 
    for word in myFile: 
     if word[0] == "v": ##Interested in only word starting with "v" 
      word_sorted = ''.join(sorted(word.rstrip())) ##Get the anagram 
      if word_sorted in dictionary: 
       print(word_sorted) 
       dictionary[word_sorted].append(word) 
      else: 
       # The case where we don't find an anagram in our dict 
       dictionary[word_sorted] = [word,]