【问题标题】:python issue in anagram script字谜脚本中的python问题
【发布时间】:2016-05-10 22:54:41
【问题描述】:

对脚本的第二次修改(以下更改)

进行了 cmets 中提到的更改(将 all 重命名为 print_all,并添加了异常,更改了下面的代码以反映相同)

但是,执行仍然无故退出

初始查询:

以下是一个尝试识别单词的各种字谜的脚本(如网站中的:http://wordsmith.org/anagram/anagram.cgi?anagram=suchindra&t=1000&a=n):

import sys
import itertools
import threading
from collections import defaultdict


words_dict = defaultdict(lambda: "")
def lower_and_nocrlf(s):
    return s.lower().strip()

def two_or_more(s):
    if len(s) >= 1:
        return 1
    else:
        return 0

def get_perms(cur_iter):
    lst = []
    for i in range(0, 10000):
        try:
            lst.append("".join(cur_iter.next()))
        except:
            break
    return lst

def get_twordlist(z):
    lst1 = []
    lst2 = []
    for i in range (1, len(z)):
        lst1.append(z[:i])
        lst2.append(z[i:])

    return lst1, lst2

def filter_dict(x):
    if x in words_dict.keys():
        return x
    else:
        return 0

def main():
    print_all = None
    word = None

    try:
        word = sys.argv[1]
        print_all = sys.argv[2]
    except:
        pass

    if word == None:
        try:
            word = sys.stdin.readline()
            print_all = sys.stdin.readline()
        except:
            pass

    if word == None:
        sys.exit(1)

    fd = open('/usr/apps/words', 'r')

    words = fd.readlines()

    fd.close()

    words_lower = map(lower_and_nocrlf, words)
    words_lower = filter(two_or_more, words_lower)
    from collections import defaultdict
    for i in words_lower:
        words_dict[i] = ""

    iter = itertools.permutations(word)

    all_permutations = []

    iters = []
    for i in range(0, 100):
        iters.append(iter)

    result = map(get_perms, iters)

    main_list = []
    for l in result:
        if l != []:
            for word in l:
                main_list.append(word)

    results = []
    try:
        main_list_len = len(main_list)
        for index in range(0, main_list_len):
            percent = (index/len(main_list)) * 100
            lst1, lst2 = get_twordlist(main_list[index])
            result1 = map(filter_dict, lst1)
            result2 = map(filter_dict, lst2)
            for index in range(0, len(result1)):
                if (result1[index] != 0) and (result2[index] != 0):
                    results.append("%s %s" % (result1[index], result2[index]))

    except KeyboardInterrupt:
        print("User stopped execution, partial results:")
        print results
        sys.exit(1)
    except Exception:
            # catches all other types of exception here
        print(sys.exc_info())
            traceback.print_exc()

    print(results)
if __name__ == "__main__":
    try:
        main()
    except:
        sys.exit(0)

【问题讨论】:

  • 顺便说一句,all 不是变量名的好选择,因为它会影响内置的 all() 函数。此外,您可以使用内置的exit() 函数而不是sys.exit()(假设您实际上需要一个退出函数......)。
  • s/results.append[result]/results.append(result)/
  • @PM2Ring 此外,all 没有在程序的其余部分中引用...
  • 谢谢@gboffi。那是第一个错误。现在我不知道还有什么问题。我修改了查询并更新了代码。我猜 filter(filter_dict, lst1, lst2) 是错误的
  • @gboffi:当然可以,所以不会造成问题,但这仍然不是一个好主意,而且对于其他阅读代码的人来说有点混乱。

标签: python anagram


【解决方案1】:

因此,您的代码显然正在执行到 print index 行,然后在块内的某处失败。异常处理程序仅捕获 KeyboardInterrupt 类型的异常 - 即当用户在其键盘上按下 Ctl+C 时。任何其他错误都将通过 sys.exit(0) 方法退出,因此您无法知道错误是什么。

我个人非常喜欢 traceback 模块来处理这些打印错误,所以我建议您将 try catch 块修改为:

import traceback

try:
    main_list_len = len(main_list)
    print main_list_len
    for index in range(0, main_list_len):
        print index
        percent = (index/len(main_list)) * 100
        lst1, lst2 = get_twordlist(main_list[index])
        result = map(filter_dict, lst1, lst2)
        results.append[result]
except KeyboardInterrupt:
    print("User stopped execution, partial results:")
    print("Exception: %s" % (sys.exc_info()))
    print results
except Exception:
    # catches all other types of exception here
    traceback.print_exc()

这将允许您调试问题,因为回溯模块将为您提供行号和错误消息。

祝你好运!

【讨论】:

  • 谢谢。几个小时后终于确定了罪魁祸首。它是 results.append[result]。应该是 results.append(result)。
  • 我仍然觉得它应该继续 for 循环,因为它与被操纵的结果无关
【解决方案2】:

好的,经过一些分析,过滤器似乎不接受多个列表。第二个问题是因为我在过滤器中使用了多个列表

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-01-13
    • 1970-01-01
    • 1970-01-01
    • 2021-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-06
    相关资源
    最近更新 更多