从给定的字符串中搜索词汇表中最大的单词匹配项

时间:2018-08-15 11:10:34

标签: regex string python-3.x list

我有一个字符串the big cat in the zoo,我的词汇中有["in the zoo", "the zoo"] 我无法直接搜索,必须搜索组合:
   1)动物园
   2)动物园
   3)在动物园里
并仅返回"in the zoo",即最大的匹配字符串 如何在python中进行反向搜索和匹配

2 个答案:

答案 0 :(得分:0)

可以尝试一些类似的方法-

str1 = "the big cat in the zoo"

vocabulary = ["in the zoo", "the zoo"]

str1 = str1.split()

for first, last in itertools.combinations(range(len(str1)), 2):
    new_str = ' '.join(str1[first:last+1])
    print (new_str)

这将为您提供输出

the big
the big cat
the big cat in
the big cat in the
the big cat in the zoo
big cat
big cat in
big cat in the
big cat in the zoo
cat in
cat in the
cat in the zoo
in the
in the zoo
the zoo

编辑它,但是要更改它以将其用于问题的状况。

答案 1 :(得分:0)

  1. 按长度降序排列列表项。

  2. 使用if (mystring.Contains(vocabularyItem)) ...

  3. 遍历列表项