2017-05-22 22 views
0

此函数旨在将从字典文件导入的所有127,000个单词与输入长度的用户进行比较。然后它应该返回等于该长度的单词量。它确实在一定程度上做到了这一点。Python - 将127,000+个单词导入列表,但函数仅返回部分结果

如果输入“15”,则返回“0”。 如果输入“4”,则返回“3078”。

我确信长度为15个字符的单词不管怎样都返回“0”。 我还要提到的是,如果我输入任何大于15的结果仍然是0时,有更大的话15

try: 
    dictionary = open("dictionary.txt") 
except: 
    print("Dictionary not found") 
    exit() 


def reduceDict(): 
    first_list = [] 

    for line in dictionary: 
     line = line.rstrip() 
     if len(line) == word_length: 
      for letter in line: 
       if len([ln for ln in line if line.count(ln) > 1]) == 0: 
        if first_list.count(line) < 1: 
         first_list.append(line) 
       else: 
        continue 
    if showTotal == 'y': 
     print('|| The possible words remaing are: ||\n ',len(first_list)) 
+0

给出一行dictionary.txt作为示例输入,以便我们可以了解输入的结构 – bigbounty

+0

在字典文件中,每行都有一个单词。即 chemotherapeutic – MLJezus

+1

你还可以详细说明为什么你需要'在线信:' – kuro

回答

2

我读的是:

if len([ln for ln in line if line.count(ln) > 1]) == 0: 

是有问题的话不能有任何重复的字母,这可以解释为什么没有找到任何单词 - 一旦你达到15,重复的信件是相当普遍的。由于这一要求并没有在说明中提到,如果我们再下降,我们可以这样写:

def reduceDict(word_length, showTotal): 
    first_list = [] 

    for line in dictionary: 
     line = line.rstrip() 

     if len(line) == word_length: 
      if line not in first_list: 
       first_list.append(line) 

    if showTotal: 
     print('The number of words of length {} is {}'.format(word_length, len(first_list))) 
     print(first_list) 

try: 
    dictionary = open("dictionary.txt") 
except FileNotFoundError: 
    exit("Dictionary not found") 

reduceDict(15, True) 

从我的Unix words文件变成了约40万字。如果我们想要恢复独特的字母要求:

import re 

def reduceDict(word_length, showTotal): 
    first_list = [] 

    for line in dictionary: 
     line = line.rstrip() 

     if len(line) == word_length and not re.search(r"(.).*\1", line): 
      if line not in first_list: 
       first_list.append(line) 

    if showTotal: 
     print('The number of words of length {} is {}'.format(word_length, len(first_list))) 
     print(first_list) 

开始返回0结果,大约有13个字母,正如人们所预料的那样。

0

在代码中,你不需要这条线 -

for letter in line:

在你的列表中理解,如果你的目的是要遍历所有词语的line使用本 -

if len([ln for ln in line.split() if line.count(ln) > 1]) == 0: 

在您将列表理解循环中的循环编码到每个字符上并检查该字符是否在line中多次出现。这样,如果您的文件包含chemotherapeutic它不会被添加到列表first_list,因为有多次出现的字母。因此,除非您的文件包含超过14个字母,且所有字母只出现一次,否则您的代码将无法找到它们。

相关问题