从文本中删除专有名词

时间:2018-01-04 21:02:53

标签: python python-3.x pandas spacy

我有一个包含数千行文本数据的df。我正在使用spaCy在该df的单个列上执行一些NLP,并尝试使用以下内容从我的文本数据中删除专有名词,停用单词和标点符号:

tokens = []
lemma = []
pos = []

for doc in nlp.pipe(df['TIP_all_txt'].astype('unicode').values, batch_size=9845,
                        n_threads=3):
    if doc.is_parsed:
        tokens.append([n.text for n in doc if not n.is_punct and not n.is_stop and not n.is_space and not n.is_propn])
        lemma.append([n.lemma_ for n in doc if not n.is_punct and not n.is_stop and not n.is_space and not n.is_propn])
        pos.append([n.pos_ for n in doc if not n.is_punct and not n.is_stop and not n.is_space and not n.is_propn])
    else:
        tokens.append(None)
        lemma.append(None)
        pos.append(None)

df['s_tokens_all_txt'] = tokens
df['s_lemmas_all_txt'] = lemma
df['s_pos_all_txt'] = pos

df.head()

但是我得到了这个错误,我不确定原因:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-34-73578fd46847> in <module>()
      6                         n_threads=3):
      7     if doc.is_parsed:
----> 8         tokens.append([n.text for n in doc if not n.is_punct and not n.is_stop and not n.is_space and not n.is_propn])
      9         lemma.append([n.lemma_ for n in doc if not n.is_punct and not n.is_stop and not n.is_space and not n.is_propn])
     10         pos.append([n.pos_ for n in doc if not n.is_punct and not n.is_stop and not n.is_space and not n.is_propn])

<ipython-input-34-73578fd46847> in <listcomp>(.0)
      6                         n_threads=3):
      7     if doc.is_parsed:
----> 8         tokens.append([n.text for n in doc if not n.is_punct and not n.is_stop and not n.is_space and not n.is_propn])
      9         lemma.append([n.lemma_ for n in doc if not n.is_punct and not n.is_stop and not n.is_space and not n.is_propn])
     10         pos.append([n.pos_ for n in doc if not n.is_punct and not n.is_stop and not n.is_space and not n.is_propn])

AttributeError: 'spacy.tokens.token.Token' object has no attribute 'is_propn'

如果我取出not n.is_propn代码按预期运行。我已经用Google搜索并阅读了spaCy文档,但到目前为止还没有找到答案。

3 个答案:

答案 0 :(得分:5)

我在Token object上看不到is_propn属性。

我认为你应该检查词性类型为PROPN reference):

from spacy.parts_of_speech import PROPN

def is_proper_noun(token):
    if token.doc.is_tagged is False:  # check if the document was POS-tagged
        raise ValueError('token is not POS-tagged')

    return token.pos == PROPN

答案 1 :(得分:2)

添加@alecxe答案。

没有需要

  • 一次填充数据框的所有行。
  • 在填充数据框时获取单独的标记,引号和pos列表。

您可以尝试:

df = pd.DataFrame(columns=['tokens', 'lemmas', 'pos'])

annotated_docs = nlp.pipe(df['TIP_all_txt'].astype('unicode').values,
                          batch_size=9845, n_threads=3)

for doc in annotated_docs:
    if doc.is_parsed:
        # Remove the tokens that you don't want.
        tokens, lemmas, pos = zip(*[(tok.text, tok.lemma_, tok.pos_) 
                                    for tok in doc if not
                                    (tok.is_punct or tok.is_stop 
                                     or tok.is_space or is_proper_noun(tok) )
                                   ]
                                  )
        # Populate the DataFrame.
        df.append({'tokens':tokens, 'lemmas':lemmas, 'pos':pos})

这是来自how to split column of tuples in pandas dataframe?的整洁的熊猫伎俩,但数据框将占用更多内存:

df = pd.DataFrame(columns=['Tokens'])

annotated_docs = nlp.pipe(df['TIP_all_txt'].astype('unicode').values,
                          batch_size=9845, n_threads=3)

for doc in annotated_docs:
    if doc.is_parsed:
        # Remove the tokens that you don't want.
        df.append([(tok.text, tok.lemma_, tok.pos_) 
                    for tok in doc if not
                    (tok.is_punct or tok.is_stop 
                     or tok.is_space or is_proper_noun(tok) )
                   ]
                  )

df[['tokens', 'lemmas', 'pos']] = df['Tokens'].apply(pd.Series)

答案 2 :(得分:0)

from nltk.tag import pos_tag
def proper_nouns():
    tagged_sent = pos_tag(speech.split())
    pn = [word for word,pos in tagged_sent if pos == 'NNP']
    pn = [x.lower() for x in pn]
    prn=list(set(pn))
    prn= pd.DataFrame({'b_words':prn,'bucket_name':'proper noun'})
    return prn
df=proper_nouns()

这里的演讲将成为您的文字!