Лемматизация данных в Интернете - PullRequest
3 голосов
/ 22 марта 2019

Предположим, у меня есть текстовый документ, такой как:

document = '<p> I am a sentence. I am another sentence <p> I am a third sentence.'

(или более сложный текстовый пример:

document = '<p>Forde Education are looking to recruit a Teacher of Geography for an immediate start in a Doncaster Secondary school.</p> <p>The school has a thriving and welcoming environment with very high expectations of students both in progress and behaviour.&nbsp; This position will be working&nbsp;until Easter with a&nbsp;<em><strong>likely extension until July 2011.</strong></em></p> <p>The successful candidates will need to demonstrate good practical subject knowledge  but also possess the knowledge and experience to teach to GCSE level with the possibility of teaching to A’Level to smaller groups of students.</p> <p>All our candidate will be required to hold a relevant teaching qualifications with QTS  successful applicants will be required to provide recent relevant references and undergo a Enhanced CRB check.</p> <p>To apply for this post or to gain information regarding similar roles please either submit your CV in application or Call Debbie Slater for more information.&nbsp;</p>' 

)

Я применяю серию методов предварительной обработки НЛП, чтобы получить «более чистую» версию этого документа, также взяв слово для каждого слова.

Я использую для этого следующий код:

stemmer_1 = PorterStemmer()
stemmer_2 = LancasterStemmer()
stemmer_3 = SnowballStemmer(language='english')

# Remove all the special characters
document = re.sub(r'\W', ' ', document)

# remove all single characters
document = re.sub(r'\b[a-zA-Z]\b', ' ', document)

# Substituting multiple spaces with single space
document = re.sub(r' +', ' ', document, flags=re.I)

# Converting to lowercase
document = document.lower()

# Tokenisation
document = document.split()

# Stemming
document = [stemmer_3.stem(word) for word in document]

# Join the words back to a single document
document = ' '.join(document)

Это дает следующий вывод для текстового документа выше:

'am sent am anoth sent am third sent'

(и этот вывод для более сложного примера:

'ford educ are look to recruit teacher of geographi for an immedi start in doncast secondari school the school has thrive and welcom environ with veri high expect of student both in progress and behaviour nbsp this posit will be work nbsp until easter with nbsp em strong like extens until juli 2011 strong em the success candid will need to demonstr good practic subject knowledg but also possess the knowledg and experi to teach to gcse level with the possibl of teach to level to smaller group of student all our candid will be requir to hold relev teach qualif with qts success applic will be requir to provid recent relev refer and undergo enhanc crb check to appli for this post or to gain inform regard similar role pleas either submit your cv in applic or call debbi slater for more inform nbsp'

)

Теперь я хочу получить вывод, подобный приведенному выше, но после того, как я применил лемматизацию, а не основание.

Однако, если я что-то упускаю, для этого необходимо разбить исходный документ на (разумные) предложения, применить POS-теги и затем реализовать лемматизацию.

Но здесь все немного сложнее, потому что текстовые данные поступают из веб-страниц и, следовательно, вы встретите много HTML-тегов, таких как <br>, <p> и т. Д.

Моя идея заключается в том, что каждый раз, когда последовательность слов оканчивается каким-либо общим знаком пунктуации (точка останова, восклицательный знак и т. Д.) Или тегом HTML, таким как <br>, <p> и т. Д., Это следует рассматривать как отдельный предложение.

Так, например, оригинал документа выше:

document = '<p> I am a sentence. I am another sentence <p> I am a third sentence.'

Должен быть разбит на что-то вроде этого:

['I am a sentence', 'I am another sentence', 'I am a third sentence']

и тогда я предполагаю, что мы будем применять POS-теги к каждому предложению, разбивать каждое предложение на слова, применять лемматизацию и .join() слова обратно к одному документу, как я делаю это с моим кодом выше.

Как я могу это сделать?

1 Ответ

1 голос
/ 22 марта 2019

Удаление HTML-тегов является общей частью уточнения текста. Вы можете использовать свои собственные правила, такие как text.replace('<p>', '.'), но есть лучшее решение: html2text . Эта библиотека может сделать всю грязную работу по улучшению HTML, например:

>>> print h.handle("<p>Hello, <a href='http://earth.google.com/'>world</a>!")
Hello, world!

Вы можете импортировать эту библиотеку в свой код Python или использовать ее как отдельную программу.

Редактировать: Вот небольшой пример цепочки, которая разбивает ваш текст на предложения:

>>> document = '<p> I am a sentence. I am another sentence <p> I am a third sentence.'
>>> text_without_html = html2text.html2text(document)
>>> refined_text = re.sub(r'\n+', '. ', text_without_html)
>>> sentences = nltk.sent_tokenize(refined_text)
>>> sentences

['I am a sentence.', 'I am another sentence.', 'I am a third sentence..']
...