首页 > 解决方案 > 比较单词列表,删除相似单词并添加到新字符串中

问题描述

我有 2 个字符串,已将其转换为单词 A 和 B 的列表。我正在尝试制作一种算法,从左侧开始选择单词。如果该单词在第二个字符串中显示为单词或单词的一部分,则将该单词添加到新的公共字符串中,并删除在第二个字符串中找到该单词的整个第一次出现。大写和小写字母被认为是不同的字母。我称这个算法为 Diff。

例子:

List A: " The quick brown fox did jump over a log"
List B: " The brown rabbit quickly did outjump the fox"

如果我要区分 A 到 B,我会得到“快速的棕色狐狸确实跳了 a”

如果我要区分 B 到 A,我会得到“棕色的狐狸”

我到目前为止的代码:

import re

a = 'The quick brown fox did jump over a log'
aa = re.sub("[^\w]", " ",  a).split()
b = 'The brown rabbit quickly did outjump the fox'
bb = re.sub("[^\w]", " ",  b).split()
print (aa)
print (bb)

上面的代码是我用来将字符串更改为单词列表的代码。

标签: pythonstringlistpython-3.6

解决方案


这可以工作

common_str = ""

a =  " The quick brown fox did jump over a log"
b = " The brown rabbit quickly did outjump the fox"
alist = a.split(" ")
blist = b.split(" ")
for item in blist:
    if item in alist:
        #add word to common string
        common_str += item + " "
        #remove from second string
        i = item + " " #item plus trailing space
        a.replace(i, "")
print(common_str)
print(a)
print(b)

推荐阅读