【发布时间】:2017-09-21 15:54:11
【问题描述】:
提前感谢您的帮助。
我有一个字符串列表
full_name_list = ["hello all","cat for all","dog for all","cat dog","hello cat","cat hello"]
我需要在每个元素与列表中的所有元素之间进行百分比匹配。例如,我需要首先将"hello all" 分解为["hello", "all"],我可以看到"hello" 在"hello cat" 中,因此匹配率为50%。这是我到目前为止所拥有的,
hello all [u'hello', u'hello all', u'hello cat', u'cat hello'] [u'all', u'hello all', u'cat for all', u'dog for all']
cat for all [u'cat', u'cat for all', u'cat dog', u'hello cat', u'cat hello'] [u'for', u'cat for all', u'dog for all'] [u'all', u'hello all', u'cat for all', u'dog for all']
dog for all [u'dog', u'dog for all', u'cat dog'] [u'for', u'cat for all', u'dog for all'] [u'all', u'hello all', u'cat for all', u'dog for all']
cat dog [u'cat', u'cat for all', u'cat dog', u'hello cat', u'cat hello'] [u'dog', u'dog for all', u'cat dog']
hello cat [u'hello', u'hello all', u'hello cat', u'cat hello'] [u'cat', u'cat for all', u'cat dog', u'hello cat', u'cat hello']
cat hello [u'cat', u'cat for all', u'cat dog', u'hello cat', u'cat hello'] [u'hello', u'hello all', u'hello cat', u'cat hello']
如您所见,每个子列表中的第一个单词包含正在搜索的子字符串,然后是包含该子字符串的元素。我能够为一个单词匹配做到这一点,并且我意识到我可以通过简单地通过单个单词之间的交集来获得双重匹配来继续这个过程,例如
cat for all [(cat,for) [u'cat for all']] [(for,all) [u'cat for all', u'dog for all']]
我遇到的问题是递归执行此操作,因为我不知道最长的字符串将有多长。另外,有没有更好的方法来做这个字符串搜索?最终我想找到匹配 100% 的字符串,因为实际上是"hello cat" == "cat hello"。我还想找到 50% 的匹配项等等。
我得到的一个想法是使用二叉树,但我该如何在 python 中执行此操作?到目前为止,这是我的代码:
logical_list = []
logical_list_2 = []
logical_list_3 = []
logical_list_4 = []
match_1 = []
match_2 = []
i = 0
logical_name_full = logical_df['Logical'].tolist()
for x in logical_name_full:
logical_sublist = [x]+x.split()
logical_list.append(logical_sublist)
for sublist in logical_list:
logical_list_2.append(sublist[0])
for split_words in sublist[1:]:
match_1.append(split_words)
for logical_names in logical_name_full:
if split_words in logical_names:
match_1.append(logical_names)
logical_list_2.append(match_1)
match_1 = []
logical_list_3.append(logical_list_2)
logical_list_2 = []
【问题讨论】:
标签: python recursion binary-search-tree