gpt4 book ai didi

python - 计算python中单词中字母之间的距离

转载 作者:太空宇宙 更新时间:2023-11-04 04:31:12 26 4
gpt4 key购买 nike

我有一个包含字母和坐标的数据集“sc”。例如,

alphabets   Y   X
q 3 1
w 3 2
e 3 3
r 3 4
t 3 5
y 3 6
u 3 7
i 3 8
o 3 9
...

我有兴趣使用毕达哥拉斯定理计算单词中连续字母之间的距离。例如,对于单词“que”,距离将为 (6 + 4) = 10。

我用 python 编写了一段代码,但我的代码运行需要将近 2 个小时。我有一个超过 500k 行的数据集。P. S. 这个词可以是字母数字。

这是我的代码:

def key_score(w):
score=0
for i in range(0,len(w)-1):
t=pd.DataFrame(list(w[i:i+2].lower()))
t.columns = ['alphabets']
u = pd.merge(sc, t, how='inner', on=['alphabets'])
v = np.sqrt(((u['X'][0] - u['X'][1])**2)+((u['Y'][0] - u['Y'][1])**2))
score = score + v
return score

任何帮助将不胜感激!

最佳答案

试试这个:

df = df.set_index('alphabet') #if alphabet is not in index
word = 'que'
np.sqrt(df.reindex([*word]).diff().abs().sum().pow(2).sum())

输出:

10

关于python - 计算python中单词中字母之间的距离,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52616884/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com