使用空格删除标点;属性

2024-05-14 21:34:22 发布

您现在位置:Python中文网/ 问答频道 /正文

目前,我正在使用下面的代码对一些使用spaCy的文本数据进行元素化和计算TF-IDF值:

lemma = []

for doc in nlp.pipe(df['col'].astype('unicode').values, batch_size=9844,
                        n_threads=3):
    if doc.is_parsed:
        lemma.append([n.lemma_ for n in doc if not n.lemma_.is_punct | n.lemma_ != "-PRON-"])
    else:
        lemma.append(None)

df['lemma_col'] = lemma

vect = sklearn.feature_extraction.text.TfidfVectorizer()
lemmas = df['lemma_col'].apply(lambda x: ' '.join(x))
vect = sklearn.feature_extraction.text.TfidfVectorizer()
features = vect.fit_transform(lemmas)

feature_names = vect.get_feature_names()
dense = features.todense()
denselist = dense.tolist()

df = pd.DataFrame(denselist, columns=feature_names)
df = pd.DataFrame(denselist, columns=feature_names)
lemmas = pd.concat([lemmas, df])
df= pd.concat([df, lemmas])

我需要去掉专有名词、标点符号和停止单词,但在我当前的代码中做这件事有些困难。我读过一些documentationother resources,但现在遇到了一个错误:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-21-e924639f7822> in <module>()
      7     if doc.is_parsed:
      8         tokens.append([n.text for n in doc])
----> 9         lemma.append([n.lemma_ for n in doc if not n.lemma_.is_punct or n.lemma_ != "-PRON-"])
     10         pos.append([n.pos_ for n in doc])
     11     else:

<ipython-input-21-e924639f7822> in <listcomp>(.0)
      7     if doc.is_parsed:
      8         tokens.append([n.text for n in doc])
----> 9         lemma.append([n.lemma_ for n in doc if not n.lemma_.is_punct or n.lemma_ != "-PRON-"])
     10         pos.append([n.pos_ for n in doc])
     11     else:

AttributeError: 'str' object has no attribute 'is_punct'

有没有一种更简单的方法可以将这些内容从文本中去掉,而不必彻底改变我的方法?

完整代码可用here


Tags: textindffordocifnamesis
1条回答
网友
1楼 · 发布于 2024-05-14 21:34:22

据我所见,这里的主要问题实际上相当简单:n.lemma_返回一个字符串,而不是Token对象。所以它没有is_punct属性。我想你要找的是n.is_punct(是否标记是标点符号)。

如果您想做得更优雅,请查看spaCy的新custom processing pipeline components(需要v2.0+)。这允许您将逻辑包装在一个函数中,当您对文本调用nlp()时,该函数将自动运行。你甚至可以更进一步,将custom attribute添加到你的Doc中,例如doc._.my_stripped_docdoc._.pd_columns之类的。这里的优点是,您可以继续使用spaCy的性能良好的内置数据结构,如Doc(以及它的视图TokenSpan)作为应用程序的“唯一真实源”。这样,就不会丢失任何信息,您将始终保留对原始文档的引用,这对于调试也非常有用。

相关问题 更多 >

    热门问题