удалите все слова, которые не являются существительными, глаголами, прилагательными, наречиями или именами собственными. просторный python - PullRequest
0 голосов
/ 26 мая 2020

Я написал приведенный ниже код и хочу распечатать слова в первых 10 предложениях, и я хочу удалить все слова, которые не являются существительными, глаголами, прилагательными, наречиями или именами собственными, но я не знаю, как? Может кто-нибудь помочь мне?

! pip install wget
import wget
url = 'https://raw.githubusercontent.com/dirkhovy/NLPclass/master/data/moby_dick.txt'
wget.download(url, 'moby_dick.txt')
documents = [line.strip() for line in open('moby_dick.txt', encoding='utf8').readlines()]

import spacy

nlp = spacy.load('en')

tokens = [[token.text for token in nlp(sentence)] for sentence in documents[:200]]
pos = [[token.pos_ for token in nlp(sentence)] for sentence in documents[:100]]
pos

1 Ответ

3 голосов
/ 26 мая 2020

Все, что вам нужно, это знать, какие символы POS используются для представления этих объектов. Вот список из документации Spacy . Этот код поможет вам выполнить это требование:

import spacy

nlp = spacy.load('en_core_web_sm') #you can use other methods
# excluded tags
excluded_tags = {"NOUN", "VERB", "ADJ", "ADV", "ADP", "PROPN"}
document = [line.strip() for line in open('moby_dick.txt', encoding='utf8').readlines()]

sentences = document[:10] #first 10 sentences
new_sentences = []
for sentence in sentences:
    new_sentence = []
    for token in nlp(sentence):
        if token.pos_ not in excluded_tags:
            new_sentence.append(token.text)
    new_sentences.append(" ".join(new_sentence))

Теперь, new_sentences имеет те же предложения, что и раньше, но без каких-либо существительных, глаголов и т. Д. c. Вы можете убедиться в этом, перебирая sentences и new_sentences, чтобы увидеть разницу:

for old_sen, new_sen in zip(sentences, new_sentences):
    print("Before:", old_sen)
    print("After:", new_sen)
    print()
Before: Loomings .
After: .

Before: Call me Ishmael .
After: me .

Before: Some years ago -- never mind how long precisely -- having little or no money in my purse , and nothing particular to interest me on shore , I thought I would sail about a little and see the watery part of the world .
After: Some -- -- or no my , and nothing to me , I I a and the the .

Before: It is a way I have of driving off the spleen and regulating the circulation .
After: It is a I have the and the .

...
...
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...