Пространство ent.label_ не может определить организацию - PullRequest
0 голосов
/ 09 марта 2020

Я использую spacy для анализа террориста, и странно, что spacy не может найти такую ​​организацию, как fatah. Код ниже

import spacy
nlp = spacy.load('en')
def read_file_to_list(file_name):
    with open(file_name, 'r') as file:
        return file.readlines()
terrorism_articles = read_file_to_list('data/rand-terrorism-dataset.txt')
terrorism_articles_nlp = [nlp(art) for art in terrorism_articles]
common_terrorist_groups = [
    'taliban', 
    'al - qaeda', 
    'hamas',  
    'fatah', 
    'plo', 
    'bilad al - rafidayn'
]

common_locations = [
    'iraq',
    'baghdad', 
    'kirkuk', 
    'mosul', 
    'afghanistan', 
    'kabul',
    'basra', 
    'palestine', 
    'gaza', 
    'israel', 
    'istanbul', 
    'beirut', 
    'pakistan'
]
location_entity_dict = defaultdict(Counter)

for article in terrorism_articles_nlp:

    article_terrorist_groups = [ent.lemma_ for ent in article.ents if ent.label_=='PERSON' or ent.label_ =='ORG']#人或者组织
    article_locations = [ent.lemma_ for ent in article.ents if ent.label_=='GPE']
    terrorist_common = [ent for ent in article_terrorist_groups if ent in common_terrorist_groups]
    locations_common = [ent for ent in article_locations if ent in common_locations]

    for found_entity in terrorist_common:
        for found_location in locations_common:
            location_entity_dict[found_entity][found_location] += 1
location_entity_dict

Я просто ничего не получаю из файла. Вот Текстовая ссылка на данные

Спасибо!

1 Ответ

1 голос
/ 09 марта 2020

Я воспроизвел ваш пример, и похоже, что вы получите пустые списки для article_terrorist_groups и terrorist_common. Следовательно, вы не получите выход (который я предполагаю), который вам требуется. Я изменил модель (для моей машины) на en_core_web_sm и заметил, что ent.label отличается от тех, которые вы указываете в операторе if в своем списке. Я почти уверен, что в этом случае вы используете spacy.load('en') или spacy.load('en_core_web_sm').

Вы используете if ent.label_=='PERSON' or ent.label_ =='ORG', что приводит к пустым спискам. Вы должны будете изменить это, чтобы это работало. По сути, в вашем понимании списка для article_terrorist_groups и terrorist_common, for l oop пытается перебрать пустой список.

Если вы посмотрите на вывод, который я опубликовал, вы увидите, что ent.label не 'PERSON' или 'ORG'

Примечание. Я бы рекомендовал добавить операторы печати (или использовать отладчик) в вашем коде время от времени проверять.

Мой код

import spacy
from collections import defaultdict, Counter
nlp = spacy.load('en_core_web_sm') # I changed this
def read_file_to_list(file_name):
    with open(file_name, 'r') as file:
        return file.readlines()

terrorism_articles = read_file_to_list('rand-terrorism-dataset.txt')
terrorism_articles_nlp = [nlp(art) for art in terrorism_articles]
common_terrorist_groups = [
    'taliban', 
    'al - qaeda', 
    'hamas',  
    'fatah', 
    'plo', 
    'bilad al - rafidayn'
]

common_locations = [
    'iraq',
    'baghdad', 
    'kirkuk', 
    'mosul', 
    'afghanistan', 
    'kabul',
    'basra', 
    'palestine', 
    'gaza', 
    'israel', 
    'istanbul', 
    'beirut', 
    'pakistan'
]
location_entity_dict = defaultdict(Counter)


for article in terrorism_articles_nlp:
    print([(ent.lemma_, ent.label) for ent in article.ents])

Вывод

[('CHILE', 383), ('the Santiago Binational Center', 383), ('21,000', 394)]
[('ISRAEL', 384), ('palestinian', 381), ('five', 397), ('Masada', 384)]
[('GUATEMALA', 383), ('U.S. Marines', 381), ('Guatemala City', 384)]

усеченный вывод в интересах длины этого ответа

...