【问题标题】:Stopword segmentation停用词分割
【发布时间】:2022-01-18 13:57:39
【问题描述】:

您好,亲爱的,我对 nltk 停用词有疑问:如果我执行循环,则检查字母而不是单词的停用词。我怎样才能改变这种行为? 一个例子:

import pandas as pd
import nltk

stopword = nltk.corpus.stopwords.words('italian')
pd.set_option('display.max_colwidth', None)

df = pd.read_csv('esempioTweet.csv', sep =',')

def remove_stop(text):
    text = [word for word in text if word not in stopword]
    return text
df['Testo_no_stop'] = df['Testo_token'].apply(lambda x: remove_stop(x))
df.head()

给定上一个这样的列:

[covid, calano, i, nuovi, contagi, e, tamponi]

我希望得到这样的输出:

[covid, calano, nuovi, contagi, tamponi]

但我的输出如下:

[v,d,n, ...]

我知道停用词作用于单个字母而不是整个单词,为什么?我确信我的 remove_stop 函数以正确的方式工作,但为什么停用词以错误的方式运行?感谢您对我的耐心等待。

【问题讨论】:

  • print stopword 它可能是一个字符串,即不是一个列表。或打印df['Testo_token'],这可能是一个词
  • @balmy 我还尝试将新字符串定义为prova = "oggi piove e non esco,但在这种情况下,停用词也作用于单个字母而不是单个单词
  • 这种情况发生在例如for ch in "I come in peace": 你会收到单独的信件。您期待更多像 for word in ["I","come","in","peace"]: 那样对单词进行迭代。请将您的 csv 的几行示例放入您的问题中。

标签: python nlp nltk stop-words


【解决方案1】:

您的代码使用for word in text,如果文本是字符串,则一次返回一个字母。

我将删除 pandas 的代码简化为无关紧要 - 稍微更改了您的 remove_stop 以使用 word in text.split(),尽管我认为 nltk 可能有一种将文本拆分为单词的方法,也许您应该使用它,例如它可能会删除 @987654323 的标点符号@不会。

import nltk

stopwords = nltk.corpus.stopwords.words('italian')

phrase = "oggi piove e non esco"

def remove_stop(text):
    global stopwords
    text = [word for word in text.split() if word not in stopwords]
    return text

res = remove_stop(phrase)
print( f"{res=}" )

输出:

res=['oggi', 'piove', 'esco']

顺便说一句,我认为您不需要 lambda,只需使用:

df['Testo_no_stop'] = df['Testo_token'].apply(remove_stop)

不要忘记您可以将调试添加到像 remove_stop() 这样的函数中,TBH 是使用 for 循环而不是不可调试的理解的一个很好的理由。

同样你可以打印stopwords 来检查它是否是一个列表。是的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多