在Python中确定句子中两个单词的距离

4
我可以帮您进行翻译。以下是需要翻译的内容:

我需要在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 中是否有任何库可以更好地完成此工作?

1
你想找到这两个单词之间的最小距离吗?在这种情况下,它是0。 - mooiamaduck
1
@mooiamaduck,理想情况下,我希望找到这两个单词之间的最小距离。问题在于上述句子中有多个“foo”和“bar”的出现,从而产生了不同的距离组合。因此,如果我还可以得到平均距离(以及最小距离),那么就可以解决问题了。 - Ashutosh Upadhyay
2个回答

4
你可以将句子拆分为单词列表,并使用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))}

@ Eugene Soldatov,请注意上述句子中出现了多个单词“foo”和“bar”,它们产生了不同的距离组合。您的代码没有考虑到最接近的一个,即“foo bar”(句子中的最后两个单词)。您的代码几乎做了与我上面的代码相同的事情。 - Ashutosh Upadhyay
@Eugene Soldatov,谢谢!它像魔法一样奏效 :) 如果我还能得到平均距离(以及您解决的最小距离),那就解决了问题。 - Ashutosh Upadhyay
@ Eugene Soldatov,非常完美!谢谢。 - Ashutosh Upadhyay
2
请注意:在编程中,句子中的单词数量通常很少,因此w in wordswords.index(w)的时间复杂度都是O(n)。您可能需要预处理words以获得更好的渐近复杂度。 - jfs
如何处理多个单词?有什么想法吗? 句子 = “您可以将句子拆分为单词列表” w1 = “您可以” w2 = “的单词” - Aman Dalmia

0
我们也可以使用正则表达式。以下代码将返回一个列表,其中包含在“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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接