【问题标题】:Removing single letter stopwords without removing the letter from words containing it删除单个字母停用词而不从包含它的单词中删除该字母
【发布时间】:2019-07-26 00:22:57
【问题描述】:

我正在尝试从我的文本中删除停用词。

我已经尝试使用下面的代码。

from nltk.corpus import stopwords
sw = stopwords.words("english")
my_text='I love coding'
my_text=re.sub("|".join(sw),"",my_text)
print(my_text)

预期结果:love coding。 实际结果:I l cng(因为 'o' 和 've' 都在停用词列表“sw”中找到)。

我怎样才能得到预期的结果?

【问题讨论】:

标签: python stop-words


【解决方案1】:

在删除停用词之前将句子拆分为单词,然后运行

from nltk import word_tokenize
from nltk.corpus import stopwords
stop = set(stopwords.words('english'))
sentence = 'I love coding'
print([i for i in sentence.lower().split() if i not in stop])
>>> ['love', 'coding']
print(" ".join([i for i in sentence.lower().split() if i not in stop]))
>>> "love coding"

【讨论】:

    【解决方案2】:

    你需要替换单词,而不是字符:

    from itertools import filterfalse
    from nltk.corpus import stopwords
    sw = stopwords.words("english")
    my_text = 'I love coding'
    my_words = my_text.split() # naive split to words
    no_stopwords = ' '.join(filterfalse(sw.__contains__, my_words))
    

    您还应该担心拆分句子、区分大小写等问题。

    有一些库可以正确执行此操作,因为这是一个常见的、重要的问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-06-22
      • 1970-01-01
      • 2019-07-03
      • 2016-04-08
      • 1970-01-01
      • 1970-01-01
      • 2012-03-15
      相关资源
      最近更新 更多