首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >查找文本中短语之间的距离

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

Stack Overflow用户
提问于 2018-11-22 10:12:16
回答 3查看 121关注 0票数 0

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

埃隆·马斯克( Elon )是一位科技企业家和投资者。他是SpaceX的创始人、首席执行官和首席设计师。埃隆·马斯克( Elon )表示,SpaceX、Tesla和SolarCity的目标围绕着他改变世界和人类的愿景。

我想数一数"Elon“和"SpaceX”之间有多少个单词。然后返回smth,就像一个有数字的列表,然后找到平均单词距离。例如,15,6。

我知道,在单词的情况下,我们可以在单词上分割文本。但是如何处理短语呢?

EN

回答 3

Stack Overflow用户

发布于 2018-11-22 10:19:47

你可能会根据点、感叹号和问号来分割你的文本,但是你的程序怎么知道短语和点之间的区别,表示缩写呢?最重要的是,你将如何处理括号?它们会被视为不同的短语吗?

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

票数 1
EN

Stack Overflow用户

发布于 2019-01-18 23:01:00

正如用户Dominique所提到的,有许多小细节您必须考虑。我做了一个简单的程序,可以找到两个单词的距离。你想要找到"Elon“和"SpaceX”之间的距离。为什么不直接找出“麝香”和"SpaceX“之间的距离呢?

注释:此示例将返回单词第一次出现之间的距离。在这个程序中,我们找到了“麝香”(第二个单词)和"SpaceX (第18个单词)“之间的距离,之间的距离是15字

埃隆·马斯克( Elon )是一位科技企业家和投资者。他是SpaceX的创始人、首席执行官和首席设计师。埃隆·马斯克( Elon )表示,SpaceX、Tesla和SolarCity的目标围绕着他改变世界和人类的愿景。

示例(Python3):

代码语言:javascript
复制
# 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.')

输出:

“麝香”和"SpaceX“之间的距离是15个字。

票数 1
EN

Stack Overflow用户

发布于 2019-01-19 00:01:26

有一些您还没有指定的逻辑,但是下面这样的内容可能会起作用:

代码语言:javascript
复制
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]

代码语言:javascript
复制
print(find_distance(phrase, "Elon Musk", "SpaceX"))

请注意,必须定义像Elon Musk is a technology Elon Musk entrepreneur ...这样的情况的行为。你想选哪一种?第一还是第二?

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53428546

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档