【发布时间】:2017-10-22 23:49:38
【问题描述】:
有两个列表,一个由一个句子的字符序列组成,另一个由单词组成。
目标是将第一个列表的项目与第二个列表的项目匹配length of li_a (len(li_a)) 次。相同的匹配词将被暂时保存为候选词。在最后的迭代过程之后,最长的单词将被选为我们的预期结果,并附加到一个新的列表中。
由于li_a 中有18 个字符,假设literation time 为18。
li_a = ['T','h','o','m','a','s','h','a','d','a','h','a','r','d','t','i','m','e']
li_words = ['a','The','Thomas','have','had','has','hard','hot','time','tea']
首先,li_a 中的第一项与li_words 匹配。
1. 'T' => li_words || li_a[0] => li_words
2. 'Th' => li_words || li_a[0]+li_a[1] => li_words
3. 'Tho' => li_words || li_a[0]+li_a[1]+li_a[2] => li_words
...
6. 'Thomas' => li_words || li_a[0]+..+li_a[5] => li_words (marks as candidate when the match is found)
...
18. 'Thomashadahardtime' => li_words || li_a[0]..li_a[17] => li_words
上面的例子展示了第一个迭代过程应该如何完成。它为我们提供了一个候选结果,即Thomas。但是接下来,li_a从第一个'T'到's'(Thomas)的项目会被扣除,
li_a = ['h','a','d','a','h','a','r','d','t','i','m','e']
应该像之前一样执行第二次迭代过程来检索下一个单词。
最后,我们的列表最终结果应该是这样的:
final_li = ['Thomas','had','a','hard','time']
尝试
以下尝试适用于查找最长匹配项,但不适用于迭代工作,并且当li_words 中缺少单词时不会给出准确的结果
def matched_substring(li1, li2):
new_li = []
tmp = ''
for a in li1:
tmp += a
count = 0
for b in li2:
if tmp == b:
count += 1
if count == 0:
tmp1 = tmp.replace(a, '')
new_li.append(tmp1)
tmp = a
if li2.__contains__(tmp):
new_li.append(tmp)
return new_li
它返回为:['Thomas', 'h', 'a', 'd', 'a', 'h', 'a', 'r', 'd', 't', 'i', 'm']
UNICODE 中的字符
string_a = "['ဒီ|စစ်|ဆေး|မှု|ကို|သီး|ခြား|လွတ်|လပ်|တဲ့|ပု|ဂ္ဂို|လ်|တ|ဦး|က|ဦး|ဆောင်|ခိုင်း|တာ|ဟာ|လူ|ထု|အ|ကျိုး|အ|တွက်|ဖြစ်|တယ်|လို့|တ|ရား|ရေး|ဝန်|ကြီး|ဌာ|န|က|ထုတ်|ပြန်|တဲ့|ကြေ|ညာ|ချက်|ထဲ|မှာ|ဖေါ်|ပြ|ထား|ပါ|တယ်']"
将上面的字符串转换为列表:
##Get rid of brackets & punctuation marks
strp_str = string_a.strip("[]")
strp_str = strp_str.strip("'")
##Now we achieve *li_a*
li_a = strp_str.split('|')
li_words 列表的剪贴板链接:mm-words.txt
##Get all the words in List
read_words = open('mm-words.txt','r')
##Achieve them in List
li_words = read_words.read().split('\n')
##Now run into function
print analyze(li_a, li_words)
【问题讨论】:
-
由于该问题具有等效的子问题,因此这是探索递归或动态编程方法的绝佳机会。
-
我认为在
li_words中做循环项目并在li_a中匹配项目会很容易