查找文本中短语之间的距离



我有一个问题,如何计算文本中短语之间的单词?例如,我有下一个文本:

埃隆·马斯克是一位科技企业家和投资者。他是太空探索技术公司的创始人、首席执行官和首席设计师。埃隆·马斯克表示,太空探索技术公司、特斯拉和太阳城的目标围绕着他改变世界和人类的愿景。

我想数一下"埃隆·马斯克"one_answers"太空探索技术公司"之间有多少单词。返回smth,就像一个有数字的列表,然后找到平均单词距离。例如,[15,6]。

我知道,在单词的情况下,我们可以根据单词拆分文本。但是短语该怎么办呢?

您可能会根据点、感叹号和问号来拆分文本,但您的程序如何知道短语之间的点和表示缩写的点的区别?除此之外,您将如何处理括号?它们是否会被视为单独的短语?

我不认为你的问题有一个直接的答案,除非你对你的短语施加一些严重的限制。

正如用户Dominique提到的,有很多小细节你必须考虑。我做了一个简单的程序,可以找到两个单词的距离。你想找到"埃隆·马斯克"one_answers"太空探索技术公司"之间的距离。为什么不找出"马斯克"one_answers"太空探索技术公司"之间的距离呢?

注意:此示例将返回单词第一次出现之间的距离。在这个程序中,我们找到了"Musk"(第2个单词(和"SpaceX"(第18个单词(之间的距离。之间的距离是15个单词

埃隆·马斯克是一位科技企业家和投资者。他是太空探索技术公司的创始人、首席执行官和首席设计师。埃隆·马斯克表示,太空探索技术公司、特斯拉和太阳城的目标围绕着他改变世界和人类的愿景。

示例(Python 3(:

# Initial sentence
phrase = 'Elon Musk is a technology entrepreneur and investor. He is the founder, CEO, and lead designer of SpaceX. Elon Musk has stated that the goals of SpaceX, Tesla, and SolarCity revolve around his vision to change the world and humanity.'
# Removes common punctuation characters
phrase = ''.join(character for character in phrase if character not in ('!', '.' , ':' , ',', '"')) # Insert punctuation you want removed
# Creates a list of split words
word_list = phrase.split()
# Words you want to find the distance between (word_1 comes first in the sentence, then word_2)
word_1 = 'Musk'
word_2 = 'SpaceX'
# Calculates the distance between word_1 and word_2
distance = (word_list.index(word_2)) - (word_list.index(word_1))
# Prints distance between word_1 and word_2
print('Distance between "' + word_1 + '" and "' + word_2 + '" is ' + str(distance - 1) + ' words.')

输出:

"马斯克"one_answers"太空探索技术公司"之间的距离是15个单词

有一些逻辑尚未指定,但以下内容可能会起作用:

def find_distance(sentence, word1, word2):
distances = []
while sentence != "":
_, _, sentence = sentence.partition(word1)
text, _, _ = sentence.partition(word2)
if text != "":
distances.append(len(text.split()))
return distances

如果你用你的句子来称呼它,你会得到你想要的[15, 6]的结果

print(find_distance(phrase, "Elon Musk", "SpaceX"))

注意,必须定义类似Elon Musk is a technology Elon Musk entrepreneur ...的情况的行为。您希望发生哪种情况?第一个还是第二个?

最新更新