提取包含法语单词的句子 "mais" return 不包含它的句子

Extracting sentences which contains the french word "mais" return sentences which do not contains it

早上好,

我试图从文件中提取包含单词 "mais" 的句子,我遇到的问题是,提取的句子根本不包含 "mais" 但有时 "jamais"。你知道为什么吗 ?我举一个小例子来说明我的问题?

在下面找到:我写的脚本使用 spacy 来标记句子,所以我只说明了一小部分。这些行跟在读取文件并将其放入列表的行之后。然后我在列表中循环以找到包含 "mais".

的 elt
    sentences_list_num = ['je ne suis pas mauvais mais lourd','je ne suis pas gentil', 'ce n\'est pas 
    plus laid', 'ce ne sera jamais bordelique']

    # Importing sentences which contains "mais"  ; result  :7477 sentences
    #word = 'mais'
    for sent in sentences_list_num:
      if 'mais' in sent:
        sentences_with_word_mais.append(sent)
      else :
        sentences_no_mais.append(sent)

    print(sentences_with_word_mais)


正在打印 return 2 句话,而它只是一个句子:

['je ne suis pas mauvais mais lourd', 'ce ne sera jamais bordelique'] # Jamais is not mais ???

因为我有一个巨大的文件,所以我从一开始就没有注意到这个错误,但是当我尝试插入另一个代码行时,我发现了这个错误。

我也使用了 "for" 但它仍然给我同样的错误。

字符串匹配不考虑单词边界。所以,根据 Python,'mais' 在 'mais' 和 'jamais' 中。您需要以某种方式指定 'mais' 需要成为它自己的词。您可以使用正则表达式:

for sent in sentences_list_num:
  if len(re.findall(r'\Wmais\W', sent)) > 0:
    sentences_with_word_mais.append(sent)
  else:
    sentences_no_mais.append(sent)

如果您已经在使用 spacy 进行标记化,您也可以遍历每个句子中的标记并查找 'mais'.