我需要确定 Python 句子中两个单词之间的接近度。例如,在下面的句子中:
the foo and the bar is foo bar
我想确定单词之间的距离foo
and bar
(确定之间出现的单词数foo
and bar
).
请注意,该词多次出现foo
and bar
在上面的句子中产生不同的距离组合。
此外,单词的顺序并不重要。确定这些单词之间的距离的最佳方法是什么?
这是我正在使用的代码:
sentence = "the foo and the bar is foo bar"
first_word_to_look = 'foo'
second_word_to_look = 'bar'
first_word = 0
second_word = 0
dist = 0
if first_word_to_look in sentence and second_word_to_look in sentence:
first_word = len(sentence.split(first_word_to_look)[0].split())
second_word = len(sentence.split(second_word_to_look)[0].split())
if first_word < second_word:
dist = second_word-first_word
else:
dist = first_word-second_word
print dist # distance
上面代码的问题在于它只考虑这两个单词的第一次出现。如果同一个句子中有更多比第一个更接近的出现,则不会考虑它。
确定接近度的最佳方法是什么? python中有没有可以更好地完成这项工作的库?
您可以将句子拆分为单词列表并使用index
的方法list
:
sentence = "the foo and the bar is foo bar"
words = sentence.split()
def get_distance(w1, w2):
if w1 in words and w2 in words:
return abs(words.index(w2) - words.index(w1))
更新以计算所有单词出现次数:
import itertools
def get_distance(w1, w2):
if w1 in words and w2 in words:
w1_indexes = [index for index, value in enumerate(words) if value == w1]
w2_indexes = [index for index, value in enumerate(words) if value == w2]
distances = [abs(item[0] - item[1]) for item in itertools.product(w1_indexes, w2_indexes)]
return {'min': min(distances), 'avg': sum(distances)/float(len(distances))}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)