【问题标题】:Python no output comparing string with imported large dictionary filePython没有输出将字符串与导入的大字典文件进行比较
【发布时间】:2013-12-27 02:55:54
【问题描述】:

我正在尝试编写代码来帮助我完成填字游戏。我遇到以下错误。

1.当我尝试将更大的文本文件与我的单词列表一起使用时,我没有收到任何输出,只有小的 3 字符串单词列表有效。

2.我的测试词列表的前两个字符串的匹配测试是肯定的。我需要它只为我的单词列表中的整个单词测试 true。 [下面代码中的解决方案]

lex.txt 包含

爸爸

添加

测试

我使用以下代码调用代码。
./cross.py 爸爸

[已解决的解决方案]这真的很慢。

#!/usr/bin/env python

import itertools, sys, re

sys.dont_write_bytecode = True
original_string=str(sys.argv[1])
lenth_of_string=len(original_string)
string_to_tuple=tuple(original_string)


with open('wordsEn.txt', 'r') as inF:
    for line in inF:
        for a in set (itertools.permutations(string_to_tuple, lenth_of_string)):
            joined_characters="".join(a)
            if re.search('\\b'+joined_characters+'\\b',line):
                print joined_characters

【问题讨论】:

  • 粘贴您的代码并选择您的代码并点击“ctrl+k”
  • 我将下面的“ifjoined_characters in line:”更改为“if re.search('\\b'+joined_characters+'\\b',line):”,这样我就可以准确匹配字符串。

标签: python helper puzzle crossword


【解决方案1】:

让我们看一下您的代码。您获取输入字符串,创建它的所有可能排列,然后在字典中查找这些排列。

在我看来,最显着的速度影响是您一遍又一遍地为字典中的每个单词创建单词的排列。这非常耗时。

除此之外,您甚至不需要排列。很明显,如果两个单词有相同的字母,则可以通过置换来相互“转换”。所以你的代码可以重新实现如下:

import itertools, sys, re
import time
from collections import Counter


sys.dont_write_bytecode = True
original_string=str(sys.argv[1]).strip()
lenth_of_string=len(original_string)
string_to_tuple=tuple(original_string)

def original_impl():
    to_return = []
    with open('wordsEn.txt', 'r') as inF:
        for line in inF:
            for a in set (itertools.permutations(string_to_tuple, lenth_of_string)):
                joined_characters="".join(a)
                if re.search('\\b'+joined_characters+'\\b',line):
                    to_return.append(joined_characters)
    return to_return

def new_impl():
    to_return = []
    stable_counter = Counter(original_string)
    with open('wordsEn.txt', 'r') as inF:
        for line in inF:
            l = line.strip()
            c = Counter(l)
            if c == stable_counter:
                to_return.append(l)
    return to_return

t1 = time.time()
result1 = original_impl()
t2 = time.time()
result2 = new_impl()
t3 = time.time()

assert result1 == result2

print "Original impl took ", t2 - t1, ", new impl took ", t3 - t2, "i.e. new impl is ", (t2-t1) / (t3 - t2), " faster"

对于一个有 100 个单词的 8 个字母的字典,输出是:

Original impl took  42.1336319447 , new impl took  0.000784158706665 i.e. new impl is  53731.0006081  faster

字典中10000条记录的原始实现所消耗的时间是无法忍受的。

【讨论】:

  • 丹斯塔尔,感谢您提供的出色解决方案。 Counter 和 iterable 仍然有点混乱。当我读到它时,我发现它如何使用字符类找到所有单词真是太神奇了。我真的不明白它对角色类有什么作用。
  • Counter 只是创建一个字典,其中键是字母,值是字符串中出现的次数。例如。 Counter("foobarbaz") = {'f': 1, 'o': 2, 'b': 2, 'a': 2, 'r': 1, 'z': 1}
猜你喜欢
  • 1970-01-01
  • 2018-10-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-12
  • 1970-01-01
  • 2015-03-14
  • 1970-01-01
相关资源
最近更新 更多