【问题标题】:Search for largest word match in a vocabulary from a given string从给定字符串中搜索词汇表中的最大单词匹配
【发布时间】:2018-08-15 11:10:33
【问题描述】:

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

【问题讨论】:

  • 到目前为止你尝试过什么?你在哪里卡住了?
  • 为什么不同时搜索in the?这种类型的最长子串问题听起来可能需要动态规划解决方案。我不认为这里真正涉及正则表达式部分。
  • 我需要最后一句话,那就是动物园的所有组合

标签: regex string python-3.x list


【解决方案1】:

可以尝试类似的方法 -

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

编辑它但是您想更改它以将其用于您的问题的条件。

【讨论】:

    【解决方案2】:
    1. 按降序对列表项进行排序。

    2. 使用if (mystring.Contains(vocabularyItem)) ...循环遍历您的列表项

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-10-18
      • 2021-09-14
      • 2013-11-28
      • 1970-01-01
      • 2011-11-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多