python - 句子比较:如何突出差异
问题描述
我在熊猫的一列中有以下字符串序列:
SEQ
An empty world
So the word is
So word is
No word is
我可以使用模糊模糊或余弦距离检查相似度。但是,我想知道如何获取有关将位置从 amore 更改为另一个的单词的信息。例如:第一行和第二行之间的相似度为0。但这里是第2行和第3行之间的相似度。它们呈现几乎相同的单词和相同的位置。如果可能的话,我想可视化这种变化(缺少单词)。与第 3 行和第 4 行类似。如何查看两行/文本之间的变化?
解决方案
假设您正在使用 jupyter / ipython 并且您只是对一行和它之前的行之间的比较感兴趣,我会做这样的事情。
一般概念是:
- 找到两个字符串之间的共享标记(通过拆分 ' ' 并找到两个集合的交集)。
- 对两个字符串之间共享的标记应用一些 html 格式。
- 将此应用于所有行。
- 将生成的数据框输出为 html 并在 ipython 中呈现。
import pandas as pd
data = ['An empty world',
'So the word is',
'So word is',
'No word is']
df = pd.DataFrame(data, columns=['phrase'])
bold = lambda x: f'<b>{x}</b>'
def highlight_shared(string1, string2, format_func):
shared_toks = set(string1.split(' ')) & set(string2.split(' '))
return ' '.join([format_func(tok) if tok in shared_toks else tok for tok in string1.split(' ') ])
highlight_shared('the cat sat on the mat', 'the cat is fat', bold)
df['previous_phrase'] = df.phrase.shift(1, fill_value='')
df['tokens_shared_with_previous'] = df.apply(lambda x: highlight_shared(x.phrase, x.previous_phrase, bold), axis=1)
from IPython.core.display import HTML
HTML(df.loc[:, ['phrase', 'tokens_shared_with_previous']].to_html(escape=False))
推荐阅读
- javascript - 如何从浏览器打字稿页面执行powershell stipt?
- html - 如何访问文件资源管理器以下载使用前端框架生成的文档
- android - 我希望我的应用程序充当蓝牙设备,并且应该对具有我的应用程序名称的其他设备可见并与其他设备共享数据
- angular - 使用 FormData.append 在对象数组中发送文件时获取未定义文件
- ruby-on-rails - 在创建我的 api 服务时,“在任何源 (Bundler::GemNotFound) 中都找不到 rake-13.0.3”
- ruby-on-rails - 是否可以获取附加在 ActiveStorage 中的图像的 url 并在 Ruby 的控制台上查看它们?
- pretty-print - 防止beeprint或prettyprint按字母顺序排列dict键
- javascript - 如何通过firebase获取网络推送通知令牌
- javascript - 如何使用 react-leaflet-pixi-overlay
- c# - 如何从 IIS 主机获取打印权限?