回溯/搜索修剪-Python中的组合词搜索
我试图创建一个过程,搜索“条目”中属于“目标”列表成员的词块。我想保留这些子集中的词序 这就是我目前所拥有的。我真的不确定如何完成这项工作,或者我的方法是否正确回溯/搜索修剪-Python中的组合词搜索,python,search,backtracking,pruning,Python,Search,Backtracking,Pruning,我试图创建一个过程,搜索“条目”中属于“目标”列表成员的词块。我想保留这些子集中的词序 这就是我目前所拥有的。我真的不确定如何完成这项工作,或者我的方法是否正确 entry="Where in the world is Carmen San Diego" goal=["Where in the", "world is", "Carmen San Diego"] 到目前为止,输出结果如下: span=1 words = entry.split(" ") initial_list= [" ".jo
entry="Where in the world is Carmen San Diego"
goal=["Where in the", "world is", "Carmen San Diego"]
到目前为止,输出结果如下:
span=1
words = entry.split(" ")
initial_list= [" ".join(words[i:i+span]) for i in range(0, len(words), span)]
x=len(initial_list)
initial_string= " ".join(initial_list)
def backtrack(A,k):
if A in goal:
print
else:
while A not in goal:
k=k-1
A= " ".join(initial_list[0:k])
if A in goal:
print A
words=A.split(" ")
firstmatch= [" ".join(words[i:i+span]) for i in range(0, len(words), span)]
newList = []
for item in initial_list:
if item not in firstmatch:
newList.append(item)
nextchunk=" ".join(newList)
backtrack(initial_string,x)
期望输出:
"Where in the"
我一直在努力寻找一个合适的算法来解决这个问题,我认为这需要回溯或搜索修剪,我不是很确定。理想情况下,解决方案适用于任何“条目”和“目标”列表。非常感谢您的评论。这里有一个想法:将您的目标列表放入trie。在trie中找到当前条目字符串的最长匹配前缀,如果找到,将其添加到输出中 然后在当前条目字符串(单词分隔符)中找到下一个空格,将当前条目字符串设置为空格后索引中的子字符串,并重复此操作,直到其为空 编辑:这里有一些代码
"Where in the"
"world is"
"Carmen San Diego"
这是你想要的吗
import string
import datrie
entry="Where in the world is Carmen San Diego"
goal=["Where in the", "world is", "Carmen San Diego"]
dt = datrie.BaseTrie(string.printable)
for i, s in enumerate(goal):
dt[s] = i
def find_prefix(current_entry):
try:
return dt.longest_prefix(current_entry)
except KeyError:
return None
def find_matches(entry):
current_entry = entry
while(True):
match = find_prefix(current_entry)
if match:
yield match
space_index = current_entry.find(' ')
if space_index > 0:
current_entry = current_entry[space_index + 1:]
else:
return
print(list(find_matches(entry)))
它只是在条目中搜索每个单词,如果你找到了,就打印出来
如果要将它们保存到列表或其他位置,可以执行以下操作:
entry="Where in the world is Carmen San Diego"
goal=["Where in the", "world is", "Carmen San Diego"]
for word in goal:
if word in entry:
print(word)
你的例子对于理解你想要做的事情并没有特别大的帮助。如果您有
entry=“abcabcdefde”
和goal=[“ab”、“dd”、“c”]
,您希望输出什么?@BrandonHumpert。在那种情况下,我希望什么也不打印。总的来说,这是一个原型。这个“目标”列表实际上代表了一系列成功的JSON查询。“条目”将是用户输入的字符串。我想用我描述的“回溯”方式将这个用户条目分解成多个查询字符串。希望这更清楚。谢谢你的帮助。不幸的是,这里的“目标”只是我用来制作原型的一个列表;实际上,它将成功的查询表示为一个api,所以我不能真正地循环所有可能成功的查询
entry="Where in the world is Carmen San Diego"
goal=["Where in the", "world is", "Carmen San Diego"]
foundwords = []
for word in goal:
if word in entry:
foundwords.append(word)