python - 将字符串(任意顺序)与大数组中的字符串进行匹配

标签 python arrays string python-2.7 string-matching

def Get_Word_List(File_=[]):
    with open("Words.txt") as File: #File of 250k+ words separated via new line 
        for Line in File:
            File_.append(Line.replace("\n",""))
    return File_

def Get_Input(Str=str):
    Str = raw_input("Input 7 letters: ")
    while len(Str) != 7:
        Str = raw_input("Input 7 letter: ")
    return Str.upper()

def Find_Words():
    Letters = Get_Input()
    List = Get_Word_List() #An Array of strings, all in uppercase
    for Word in List:
        pass

我正在尝试以任意顺序匹配字符串(最大长度为 7),例如“ZZAFIEA”可以将“FIZZ”或“FEZ”赋予大小为 250k+ 的数组中的一个或多个单词,但我不能想办法做到这一点,我已经尝试了各种方法,感谢任何帮助

最佳答案

这是一个非常好的解决方案:

from collections import Counter


def counter_is_subset(x, y):
    # If subtracting y from x doesn't return an empty Counter,
    # x is NOT a subset of y.
    return not (x - y)


def find_buildable_words(words, letters):
    letters = Counter(letters)

    for word in words:
        if counter_is_subset(Counter(word), letters):
            yield word


words = ['BLAH', 'FIZZ', 'FEZ', 'FOO', 'FAZE', 'ZEE']
letters = 'ZZAFIEA'

buildable_words = find_buildable_words(words, letters)

for word in buildable_words:
    print(word)

在我的计算机上,对于 250,000 个单词的列表,运行时间约为 1.2 秒。

关于python - 将字符串(任意顺序)与大数组中的字符串进行匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32237657/

相关文章:

python - 来自 os.listdir() 的非字母数字列表顺序

python - 即使我先尝试启动过程,过程也会在调用函数后启动

c++ - 具有动态分配大小和预定大小的简单数组内存分配

java - 在 Java 中使用另一个方法中的变量

string - 如果两个键相同但值不同,谁能解释如何打印所有键?

java - 更改 python 脚本中的 $JAVA_HOME

java - 在 Android 应用程序上运行 python

arrays - 分区求和算法

java - 正则表达式测试字符串是否包含数字

java - 字符串变量的哈希码唯一性