【问题标题】:Extracting sentences which contains the french word "mais" return sentences which do not contains it提取包含法语单词“mais”的句子,返回不包含它的句子
【发布时间】:2020-05-11 15:06:35
【问题描述】:

早上好,

我正在尝试从文件中提取包含单词“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)


打印返回 2 个句子,而它只是一个句子:

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

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

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

【问题讨论】:

  • 你应该使用正则表达式来查找整个单词。
  • 实际上,mais 在里面 - 在jamais :) 如果你想提取这个词,作为一个词,mais 而不是另一个词的一部分,你需要使用更“聪明”的东西(例如,用空格检查单词)

标签: python python-3.x list list-comprehension dictionary-comprehension


【解决方案1】:

字符串匹配不考虑单词边界。因此,根据 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”。

【讨论】:

  • 您好,如果我有一个例如 ['trop manger', 'pas trop bon'] 的术语列表,我还有一个问题,如何使用正则表达式在列表中循环,然后如果单词存在,请在我的句子列表中搜索。我使用了 for 循环,但它提取了包含“manger”的句子,而我只想要句子中的“trop manger”。您提供的解决方案很好,但我怎样才能用单词列表转置它。
猜你喜欢
  • 2013-04-08
  • 1970-01-01
  • 2014-07-11
  • 2013-09-02
  • 2021-01-22
  • 2017-04-27
  • 1970-01-01
相关资源
最近更新 更多