【问题标题】:compare list of words, similar words deleted and added into new string比较单词列表,删除相似单词并添加到新字符串中
【发布时间】:2019-02-06 22:41:31
【问题描述】:

我有 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)

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

【问题讨论】:

标签: python string list python-3.6


【解决方案1】:

这可以工作

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)

【讨论】:

  • 这确实有效,但是,这从 B 到 A 的差异,有没有办法可以从 A 到 B 差异?从 A 到 B 的结果应该是“那只敏捷的棕狐确实跳了 a”
  • 我刚刚编辑了代码。它现在应该这样做。如果可行,请您投票并接受我的回答。
  • 以前的输出是“The brown fox did”,现在是“the brown did fox”。唯一改变的是输出中的最后两个单词
【解决方案2】:
a = 'The quick brown fox did jump over a log'
aa = a.split(" ")
b = 'The brown rabbit quickly did outjump the fox'
bb = b.split(" ")
common = []
for i in aa:
    for j in bb:
        if (i == j):
            common.append(j)
            break
print(" ".join(common))

输出将是“棕狐”

a = 'The quick brown fox did jump over a log'
aa = a.split(" ")
b = 'The brown rabbit quickly did outjump the fox'
bb = b.split(" ")
common = []
for i in bb:
    for j in aa:
        if (i == j):
            common.append(j)
            break
print(" ".join(common))

输出是“The brown did fox”

【讨论】:

  • 你已经完成了从 B 到 A 的 Diff,有没有办法从列表 A 到 B 做到这一点?
  • 只需将 for 循环互换,从 aa 到 bb,从 bb 到 aa。
  • 它看起来像这样吗: a = '这只快速的棕色狐狸确实跳过了一个圆木' aa = a.split(" ") b = '棕色兔子很快就跳过了狐狸' bb = b.split(" ") common = [] for i in bb: for j in aa: if (i == j): common.append(i) break print(common)
  • 是的,这将为您提供 A 到 B 的差异
  • 它给了我相同的输出,即使在交换之后
猜你喜欢
  • 1970-01-01
  • 2021-05-09
  • 2016-06-10
  • 1970-01-01
  • 2023-02-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多