确定 Python 中句子中 2 个词之间的接近度

Determining proximity between 2 words in a sentence in Python

我需要确定 Python 中句子中 2 个词之间的接近度。例如,在下面的句子中:

the foo and the bar is foo bar

我想确定单词 foobar 之间的距离(确定出现在 foobar 之间的单词数)。

请注意,在上面的句子中多次出现单词 foobar,从而产生不同的距离组合。

另外,单词的顺序应该无关紧要。确定这些词之间距离的最佳方法是什么?

这是我使用的代码:

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 中有没有图书馆可以更好地完成这项工作?

您可以将句子拆分为单词列表并使用 listindex 方法:

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))}

我们也可以使用正则表达式。下一行将 return 一个列表,其中 foo 和 bar 之间出现的单词数

import re
sentence = "the foo and the bar is foo bar"
first_word_to_look = 'foo'
second_word_to_look = 'bar'
word_length = [len(i.split())-2 for i in re.findall(r'foo.*?bar',sentence)]
print word_length