【问题标题】:Skipping tuples without attributes Python NLTK跳过没有属性的元组 Python NLTK
【发布时间】:2020-08-21 02:40:42
【问题描述】:

我有一个主要用于自然语言工具包的脚本。它通过使用 NLTK 对单个单词进行标记和标记(分类)来工作。

当我的列表包含名称和实体时,它可以正常工作。

如果列表中包含诸如“The”、“a”、“and”等词性文章,则会出现问题。

这些词不会收到来自 NLTK 的标签(人员、组织、地理位置等)

我的问题是,有没有一种方法可以跳过元组,因为它们不会返回标签属性,所以会报错?

示例数据框:

Order   Text    results
0   0   John    
1   1   Paul    
2   2   George  
3   3   Ringo   

(显然不完美,但总比没有好)

代码:

for i in range(len(text)):
    SENT_DETECTOR = nltk.data.load('tokenizers/punkt/english.pickle')
    ne_tree = nltk.ne_chunk(pos_tag(word_tokenize(text[i])))
    df['results'][i] = ne_tree[0].label()
print(df)

输出:

   Order    Text results
0      0    John  PERSON
1      1    Paul  PERSON
2      2  George     GPE
3      3   Ringo     GPE

示例数据框 2:

   Order    Text
0      0    John
1      1    Paul
2      2  George
3      3      to

错误:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-6-dff2775636f0> in <module>
      2     SENT_DETECTOR = nltk.data.load('tokenizers/punkt/english.pickle')
      3     ne_tree = nltk.ne_chunk(pos_tag(word_tokenize(text[i])))
----> 4     df['results'][i] = ne_tree[0].label()
      5 print(df)

AttributeError: 'tuple' object has no attribute 'label'

“to”导致它崩溃,因为“to”不会得到标签。如果我要处理数千个单词,那么找到所有会导致它崩溃的单词并手动删除它们是不切实际的。理想情况下,我想跳过有问题的行,但我不确定是否可能。

感谢您的帮助。

【问题讨论】:

  • try/catchcontinue 的错误处理怎么样?

标签: python python-3.x pandas jupyter-notebook nltk


【解决方案1】:

第一个建议是删除停用词(to、the、a 等)。示例代码为:

from nltk.corpus import stopwords, wordnet    
stop_words = set(stopwords.words('english'))
df['TextRemovedStopWords'] = df['Text']
df.loc[df['Text'].isin(stop_words),'TextRemovedStopWords'] = None

之后你可以使用 try 和 except 来处理边缘情况

from nltk.tokenize import word_tokenize
from nltk import pos_tag
import nltk
nltk.download('maxent_ne_chunker')
def get_result(text):
    if text is not None:
        try:
            ne_tree = nltk.ne_chunk(pos_tag(word_tokenize(text)))
            return ne_tree[0]
        except Exception as e: 
            print(e, text)
            return None
    else:
        return None
df['results'] = df['TextRemovedStopWords'].apply(lambda x:get_result(x))

您也可以跳过删除停用词部分,但通常最好始终删除停用词。希望对您有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-28
    • 2016-05-05
    • 1970-01-01
    • 1970-01-01
    • 2014-07-14
    • 1970-01-01
    • 1970-01-01
    • 2016-05-22
    相关资源
    最近更新 更多