如果字符串由单词列表中的单词组成,则匹配不带空格的字符串

2024-06-16 11:20:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个单词列表存储在一个列表中:

[
    'investment',
    'property',
    'something',
    'else',
    'vest'
]

我还有一个字符串列表,就像这样

[
    'investmentproperty',
    'investmentsomethingproperty',
    'investmentsomethingelseproperty',
    'abcinvestmentproperty',
    'investmentabcproperty'
]

给定这个单词列表和字符串列表,我需要从单词列表中确定哪些字符串只包含单词,并确定这些单词的最大数量。你知道吗

在上面的示例中,如果最大字数为3,则只有字符串列表中的前两项匹配(即使单词“vest”位于“investment”中)。你知道吗

这个例子简化了单词列表和字符串列表-实际上有成千上万的单词和成千上万的字符串。所以这需要执行。所有字符串都不包含空格。你知道吗

我试过构造一个正则表达式,比如:

^(?:(word1)|(word2)|(word3)){1,3}$

但是对于单词列表中的单词数量(目前为10000个)来说,这个速度非常慢。你知道吗

谢谢


Tags: 字符串示例列表数量property单词elsesomething
3条回答

我想这是你的例外

代码:

strings = [
    'investmentproperty',
    'investmentsomethingproperty',
    'investmentsomethingelseproperty',
    'abcinvestmentproperty',
    'investmentabcproperty'
]
words = [
    'investment',
    'property',
    'something',
    'else'
]
new_words =filter(lambda x: [x for i in words if x in i and x != i] == [], words)
res = list()
for string in strings:
    len_string = len(string)
    in_words = []
    for w in new_words:
        if w in string:
            in_words.append(w)
    if len(''.join(in_words)) == len_string:
        res.append(string)
print res

输出:

['investmentproperty', 'investmentsomethingproperty', 'investmentsomethingelseproperty']

你预计有多少时间?我测试了以下代码:

_list = ['investmentproperty'] * 100000
_dict = [
    'investment',
    'property',
    'something',
    'else'
] * 1000
regex = re.compile("^(?:" + "|".join(_dict) + "){1,3}$")

for i in _list:
    result = regex.match(i)
#cost 5.06s

for i in _list:
    result = re.match("^(?:" + "|".join(_dict) + "){1,3}$", i)
#cost 11.04s

我认为10万长度的列表和4000长度的字典,这是一个不错的表现,对吧?你知道吗

如果我的两分钱很重要的话,我会把包含你在字典里要找的关键词的单子翻过来,这样你就不必不断地重复两个单子了。你知道吗

哦,我忘了看aththisAho–Corasick算法,这可能对你有很大帮助

如果不感兴趣,请按以下步骤操作

1-如果要保留两个列表,请查看here

matchers = ['investment', 'property', 'something', 'else', 'vest']
matching = [s for s in my_list if any(xs in s for xs in matchers)]

2-也许吧

reduce((lambda x, y: x+len(filter((lambda z, x=y: z == x), list2))), list1, 0)

3-this听起来也很有趣,看起来是regex的一个很好的替代品

对于限制匹配数的其他要求,也许可以添加一个while循环,当匹配数达到时该循环中断。在使用字典的情况下,将要查找的单词作为键,并将其所有值设置为1,每次找到单词时都添加值,直到达到目标为止。你知道吗

相关问题 更多 >