阻止 spacy 删除拆分字符串中的停用词

问题描述 投票:0回答:1

我正在尝试使用 spacy 从 csv 创建的熊猫数据框中删除停用词。 我的问题是我正在尝试解释可能混合了单词和数字的单词。

我的问题:

如果一个数字分隔一个词,使其包含一个停用词, 它将删除单词的那部分。

    Ex. With stop word at the end
        Input: 'co555in'
        Breaks up the word, separating it in 'co'+ 555 + 'in'
        Removes 'in' because it is a stop word.
        Output: 'co555'

    Ex. Without stop word at the end
        Input: 'co555inn'
        Breaks up the word, separating it in 'co'+ 555 + 'inn'
        Will not remove 'inn' because it is not a stop word.
        Output: 'co555inn'

当前实施:

    df[col] = df[col].apply(lambda text: 
            "".join(token.lemma_ for token in nlp(text) 
            if not token.is_stop))

所以我想要的是能够解释混合的数字和单词,如果数字将字符串分隔开以使其包含停用词,则无需 spacy 过滤掉单词的部分。

python nlp spacy stop-words
1个回答
1
投票

可以将token拆分成多个段,使用spacy库检查段中是否有停用词。我创建了一个名为

tokens_list
的列表,它存储了不是停用词的每个词。

之后,您可以通过遍历

tokens_list
中的每个词形还原标记,然后遍历标记中的每个字符来创建过滤器,以返回排除标点符号的完全格式化的单词。我创建了一个名为
good_tokens
的列表,它存储并返回这些格式化的单词。

这是我的

remove_stopwords
方法,其中包含一些我用于测试的附加代码。

import spacy
import pandas as pd

nlp = spacy.load('en_core_web_sm')

def remove_stopwords(text):
"""
Removes stop words from a text source
"""
    tokens = nlp(text)
    tokens_list = []
    for token in tokens:
        if not token.is_stop:
            tokens_list.append(token)
        elif len(token.text.split()) > 1:
            segmented_tokens = token.text.split()
            segmented_tokens_list = []
            for segmented_token in segmented_tokens:
                if not nlp.vocab[segmented_token].is_stop:
                    segmented_tokens_list.append(segmented_token)
            tokens_list.extend(segmented_tokens_list)
    good_tokens = []
    for token in tokens_list:
        good_token = True
        for character in token.lemma_:
            if not (character.isalnum() or character.isspace()) or character in ".,?!":
                good_token = False
                break
        if good_token:
            good_tokens.append(token.lemma_.rstrip(".,?!"))
    return " ".join(good_tokens)

df = pd.read_csv('input_file.csv') # replace with your CSV file
df['text'] = df['text'].apply(remove_stopwords)
df.to_csv('output_file.csv', index=False) # replace with your desired output file name
© www.soinside.com 2019 - 2024. All rights reserved.