python - 比较单词列表,删除相似单词并添加到新字符串中
问题描述
我有 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)
上面的代码是我用来将字符串更改为单词列表的代码。
解决方案
这可以工作
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)
推荐阅读
- c# - 使用 Nest 删除/取消索引设置
- javascript - “使用严格”在使用 Visual Studio Code 的 ES6 上不起作用
- reactjs - 如何在 React 中禁用热加载
- facebook - 此应用程序已被货币化:您尝试添加的应用程序已被 Facebook 受众网络中的企业货币化?
- html - Firefox 和 Chrome 的行高不同
- python - 单击浏览器上的按钮时如何关闭或终止我的 Django 应用程序
- python-3.x - 需要 Pycharm 配置帮助才能在 UNIX 中运行 Python 脚本
- javascript - 为什么 NextJS 的 getStaticPaths 在我运行下一个构建时会抛出错误?
- admob - 托管用户没有 AdSense 帐户
- c++ - 我应该如何修复我的 BMP280 传感器或 Arduino 代码以获得输出?