【问题标题】:Python extracting sentence containing 2 words with conditions of window sizePython在窗口大小条件下提取包含2个单词的句子
【发布时间】:2020-10-10 20:03:20
【问题描述】:

我遇到了与此链接中讨论的相同的问题 Python extracting sentence containing 2 words

但不同之处在于我只需要在定义大小的窗口搜索中提取包含这两个单词的句子。例如:

sentences = [ 'There was peace and happiness','hello every one',' How to Find Inner Peace ,love and Happiness ','Inner peace is closely related to happiness']

search_words= ['peace','happiness']
windows_size = 3  #search only the three words after the 1est word 'peace'
#output must be :
output= ['There was peace and happiness',' How to Find Inner Peace love and Happiness ']

【问题讨论】:

  • 解释清楚一点。您的输出不符合条件。
  • 我没有看到输出与条件不匹配的地方,对于输出中的第一句话:'幸福在窗户的第二个位置,所以它满足条件,并且在输出的第二句:'幸福在第三位,它满足条件,所以它是真的。输入句子中的最后一句话在哪里:“幸福”这个词在第 5 位,所以我们不接受它。窗口计数从位置 i+1 开始。我希望它更清楚?

标签: python regex string list find


【解决方案1】:

这是一个粗略的解决方案。

def search(sentences, keyword1, keyword2, window=3):
    res = []
    for sentence in sentences:
        words = sentence.lower().split(" ")
        if keyword1 in words and keyword2 in words:
            keyword1_idx = words.index(keyword1)
            keyword2_idx = words.index(keyword2)
            if keyword2_idx - keyword1_idx <= window:
                res.append(sentence)
    return res

给定一个sentences 列表和两个关键字keyword1keyword2,我们一个一个地遍历sentences 列表。我们将句子拆分为单词,假设单词由一个空格分隔。然后,在对words 列表中是否存在两个关键字进行粗略检查后,我们在words 中找到每个关键字的索引,以确保索引最多相隔window 单词在window 单词中靠得很近。我们只将满足此条件的句子附加到res 列表中,并返回该结果。

【讨论】:

  • 非常感谢,这非常有帮助非常简单。
  • 很高兴它有帮助!
猜你喜欢
  • 2013-09-02
  • 2013-04-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-11
  • 1970-01-01
相关资源
最近更新 更多