从句子中找到并删除一个单词(在单词匹配之间)python

find and remove a word from sentence(in between the word matching) python

我有如下句子

mainsentence="My words aren't available give didn't give apple and did happening me"

stopwords=['are','did','word', 'able','give','happen']

如果任何单词与中间的单词匹配则要删除(例如:"word" 应匹配 "words" 并将其删除,"did" 应匹配 "didn't" 并将其删除, 'able' 应该删除 "available" 因为 'able' 词在 'available'

finalsentence="My apple and me"

尝试使用以下代码,但

querywords = mainsentence.split()
resultwords  = [word for word in querywords if word.lower() not in stopwords]
result = ' '.join(resultwords)
print(result)

但它只适用于完全匹配。

请帮助我。

下面的代码将满足您在问题中所述的要求,但结果不太可能是您想要的。 代码的一般基础结构应该是正确的,但您可能希望更改部分匹配的条件 (stopword in testword):

def filter_out_stopwords(text, stopwords):
    result = []
    for word in text.split():
        testword = word.lower()
        flag = True
        for stopword in stopwords:
            if stopword in testword:
                flag = False
                break
        if flag:
            result.append(word)
    return result


' '.join(filter_out_stopwords("My words aren't available give didn't give apple and did happening me", ['are', 'did', 'word', 'able', 'give', 'happen']))
# "My apple and me"

或者,使用列表理解和 all()any() 可以等效使用):

def filter_out_stopwords(text, stopwords):                                                                                                   
    return [
        word for word in text.split()
        if all(stopword not in word.lower() for stopword in stopwords)]


' '.join(filter_out_stopwords("My words aren't available give didn't give apple and did happening me", ['are', 'did', 'word', 'able', 'give', 'happen']))
# "My apple and me"

您可以执行以下操作:

>>> ' '.join([word for word in mainsentence.split() if not any([stopword in word for stopword in stopwords])])
'My apple and me'

编辑:这不需要双向检查,只需查看单词是否包含停用词
EDIT2:使用更新的问题参数更新结果

不区分大小写的版本:

' '.join([word for word in mainsentence.split() if not any([stopword.lower() in word.lower() for stopword in stopwords])])

您遇到的问题可以通过以下步骤得到可持续的解决方案。

  1. 展开单词,例如我有 -> 我有,没有 -> 没有。查看 pycontractions
  2. 使用词元来获取每个词的基本形式,即将一个词的形式转换为其词根形式。例:玩,玩,玩成了玩。让我们将语料库的当前状态称为干净语料库。查看 lemmatization.
  3. 现在从干净的语料库中删除所有停用词。

您可能还会发现我写的 text cleaning module 很有趣,其中还包括拼写校正,可用于制作文本清理管道。

您可以使用正则表达式的强大功能来解决这类问题。

import re

你可以这样得到所有的数学单词:

words = re.findall(r'[a-z]*did[a-z]*', mainsentence)

你也可以替换它们:

re.sub(r'[a-z]*able[a-z]* ', '', mainsentence)

所以最终答案:

mainsentence="My words aren't available give didn't give apple and did happening me"

stopwords=['are','did','word', 'able','give','happen']

for word in stopwords:
    mainsentence = re.sub(fr'[a-z\']*{word}[a-z\']* ', '', mainsentence)
# My apple and me