Модуль TextaCy в Python

Могу ли я стать полноценным разработчиком Python Изучение

В этой статье мы познакомимся с модулем TextaCy в Python, который обычно используется для выполнения различных задач НЛП с текстами. Он построен на модуле SpaCy в Python.

Вот некоторые из особенностей модуля TextaCy:

  • Он обеспечивает возможность очистки и предварительной обработки текста путем замены и удаления знаков препинания, лишних пробелов, цифр и т. д. из текста перед его обработкой с помощью spaCy.
  • Он включает в себя автоматическое определение языка, токенизацию и векторизацию документов, а затем обучение и интерпретацию тематических моделей.
  • Пользовательские расширения могут быть добавлены для расширения основной функциональности spaCy для работы с одним или несколькими документами.
  • Загрузите подготовленные наборы данных, которые содержат как текстовое содержимое, так и информацию, например комментарии Reddit, выступления в Конгрессе и исторические книги.
  • Он предоставляет возможность извлекать такие функции, как n-граммы, сущности, аббревиатуры, ключевые фразы и триплеты SVO, в виде структурированных данных из обработанных документов.
  • Строки и последовательности можно сравнивать, используя множество схожих показателей.
  • Вычисляет читаемость текста и данные о лексическом разнообразии, такие как соотношение типов и токенов, легкость многоязычного чтения по Флешу и уровень оценок по Флешу-Кинкейду.

Установка модуля TextaCy:

Мы можем установить модуль textaCy, используя pip.

pip install textacy

Если кто-то использует conda, напишите следующую команду:

conda install -c conda-forge textacy

Примеры некоторых его функций:

Здесь мы увидим некоторые примечательные особенности модуля textaCy.

Удалить знаки препинания

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

Python3

from textacy import preprocessing
 
 
ex = """
Now is the winter of our discontent
Made glorious summer by this sun of York;
And all the clouds that lour'd upon our house
In the deep bosom of the ocean buried.
Now are our brows bound with victorious wreaths;
Our bruised arms hung up for monuments;
Our stern alarums changed to merry meetings,
Our dreadful marches to delightful measures.
Grim-visaged war hath smooth'd his wrinkled front;
And now, instead of mounting barded steeds
To fright the souls of fearful adversaries,
He capers nimbly in a lady's chamber
To the lascivious pleasing of a lute.
But I, that am not shaped for sportive tricks,
Nor made to court an amorous looking-glass;
I, that am rudely stamp'd, and want love's majesty
To strut before a wanton ambling nymph;
I, that am curtail'd of this fair proportion,
"""
 
# Remove Punctuation
rm_punc = preprocessing.remove.punctuation(ex)
 
print(rm_punc)

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

Вывод:

Now is the winter of our discontent
Made glorious summer by this sun of York 
And all the clouds that lour d upon our house
In the deep bosom of the ocean buried 
Now are our brows bound with victorious wreaths 
Our bruised arms hung up for monuments 
Our stern alarums changed to merry meetings 
Our dreadful marches to delightful measures 
Grim visaged war hath smooth d his wrinkled front 
And now  instead of mounting barded steeds
To fright the souls of fearful adversaries
He capers nimbly in a lady s chamber
To the lascivious pleasing of a lute
But I  that am not shaped for sportive tricks
Nor made to court an amorous looking glass
I  that am rudely stamp d  and want love s majesty
To strut before a wanton ambling nymph
I  that am curtail d of this fair proportion

Мы можем удалить ненужные пробелы из нашего текста. Он удалит все лишние пробелы, которые у нас есть, и сократит их все до одного пробела после каждого слова.

Python3

from textacy import preprocessing
 
 
ex = """
Now is the winter of our      discontent
Made glorious summer by this sun of York;
And all the clouds that lour'd upon our house
In the         deep bosom of the ocean buried.
Now are our brows bound with victorious wreaths;
Our bruised arms hung up for monuments;
Our stern        alarums changed to merry meetings,
Our dreadful marches to delightful measures.
Grim-visaged war hath smooth'd his wrinkled front;
And now, instead of       mounting barded steeds
To fright the souls of fearful adversaries,
He capers nimbly in a lady's chamber
To the lascivious pleasing of a lute.
But I,       that am not shaped for sportive tricks,
Nor made to court an amorous looking-glass;
I, that am rudely stamp'd, and want love's majesty
To strut        before a wanton ambling nymph;
I, that am curtail'd of this fair proportion,
"""
 
# Remove Whitespace
rm_wsp = preprocessing.normalize.whitespace(ex)
 
print(rm_wsp)

Здесь мы использовали класс normalize и метод пробелов для удаления пробелов.

Вывод:

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

Now is the winter of our discontent
Made glorious summer by this sun of York;
And all the clouds that lour'd upon our house
In the deep bosom of the ocean buried.
Now are our brows bound with victorious wreaths;
Our bruised arms hung up for monuments;
Our stern alarums changed to merry meetings,
Our dreadful marches to delightful measures.
Grim-visaged war hath smooth'd his wrinkled front;
And now, instead of mounting barded steeds
To fright the souls of fearful adversaries,
He capers nimbly in a lady's chamber
To the lascivious pleasing of a lute.
But I, that am not shaped for sportive tricks,
Nor made to court an amorous looking-glass;
I, that am rudely stamp'd, and want love's majesty
To strut before a wanton ambling nymph;
I, that am curtail'd of this fair proportion,

Удаление пунктуации и пробелов вместе

Python3

from textacy import preprocessing
 
 
ex = """
Now is the winter of our      discontent
Made glorious summer by this sun of York;
And all the clouds that lour'd upon our house
In the         deep bosom of the ocean buried.
Now are our brows bound with victorious wreaths;
Our bruised arms hung up for monuments;
Our stern        alarums changed to merry meetings,
Our dreadful marches to delightful measures.
Grim-visaged war hath smooth'd his wrinkled front;
And now, instead of       mounting barded steeds
To fright the souls of fearful adversaries,
He capers nimbly in a lady's chamber
To the lascivious pleasing of a lute.
But I,       that am not shaped for sportive tricks,
Nor made to court an amorous looking-glass;
I, that am rudely stamp'd, and want love's majesty
To strut        before a wanton ambling nymph;
I, that am curtail'd of this fair proportion,
"""
 
# Remove Punctuation
rm_punc = preprocessing.remove.punctuation(ex)
 
# Remove Whitespace
rm_wsp = preprocessing.normalize.whitespace(ex)
 
# Remove Punctuation and Whitespace both
rm_all = preprocessing.normalize.whitespace(rm_punc)
 
print(rm_all)

Вывод:

Now is the winter of our discontent
Made glorious summer by this sun of York
And all the clouds that lour d upon our house
In the deep bosom of the ocean buried
Now are our brows bound with victorious wreaths
Our bruised arms hung up for monuments
Our stern alarums changed to merry meetings
Our dreadful marches to delightful measures
Grim visaged war hath smooth d his wrinkled front
And now instead of mounting barded steeds
To fright the souls of fearful adversaries
He capers nimbly in a lady s chamber
To the lascivious pleasing of a lute
But I that am not shaped for sportive tricks
Nor made to court an amorous looking glass
I that am rudely stamp d and want love s majesty
To strut before a wanton ambling nymph
I that am curtail d of this fair proportion

Разделить текст

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

Python3

from textacy import preprocessing
from textacy import extract
 
 
ex = """
Now is the winter of our      discontent
Made glorious summer by this sun of York;
And all the clouds that lour'd upon our house
In the         deep bosom of the ocean buried.
Now are our brows bound with victorious wreaths;
Our bruised arms hung up for monuments;
Our stern        alarums changed to merry meetings,
Our dreadful marches to delightful measures.
Grim-visaged war hath smooth'd his wrinkled front;
And now, instead of       mounting barded steeds
To fright the souls of fearful adversaries,
He capers nimbly in a lady's chamber
To the lascivious pleasing of a lute.
But I,       that am not shaped for sportive tricks,
Nor made to court an amorous looking-glass;
I, that am rudely stamp'd, and want love's majesty
To strut        before a wanton ambling nymph;
I, that am curtail'd of this fair proportion,
"""
 
# Remove Punctuation
rm_punc = preprocessing.remove.punctuation(ex)
 
# Remove Whitespace
rm_wsp = preprocessing.normalize.whitespace(ex)
 
# Remove Punctuation and Whitespace both
rm_all = preprocessing.normalize.whitespace(rm_punc)
 
# Extracting text
ext = list(extract.keyword_in_context(
    rm_all, 'I', window_width=20, pad_context=True))
 
print(ext)

Вывод:

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

[('                Now ', 'i', 's the winter of our '), 
('        Now is the w', 'i', 'nter of our disconte'), 
(' the winter of our d', 'i', 'scontent\nMade glorio'), 
('discontent\nMade glor', 'i', 'ous summer by this s'), 
('lorious summer by th', 'i', 's sun of York \nAnd a'), 
('ur d upon our house\n', 'I', 'n the deep bosom of '), 
('som of the ocean bur', 'i', 'ed \nNow are our brow'), 
('re our brows bound w', 'i', 'th victorious wreath'), 
('r brows bound with v', 'i', 'ctorious wreaths \nOu'), 
('ws bound with victor', 'i', 'ous wreaths \nOur bru'), 
('ous wreaths \nOur bru', 'i', 'sed arms hung up for'), 
('hanged to merry meet', 'i', 'ngs \nOur dreadful ma'), 
('adful marches to del', 'i', 'ghtful measures \nGri'), 
('ightful measures \nGr', 'i', 'm visaged war hath s'), 
('ful measures \nGrim v', 'i', 'saged war hath smoot'), 
(' war hath smooth d h', 'i', 's wrinkled front \nAn'), 
('hath smooth d his wr', 'i', 'nkled front \nAnd now'), 
('kled front \nAnd now ', 'i', 'nstead of mounting b'), 
('now instead of mount', 'i', 'ng barded steeds\nTo '), 
(' barded steeds\nTo fr', 'i', 'ght the souls of fea'), 
(' of fearful adversar', 'i', 'es \nHe capers nimbly'), 
('rsaries \nHe capers n', 'i', 'mbly in a lady s cha'), 
('s \nHe capers nimbly ', 'i', 'n a lady s chamber\nT'), 
(' chamber\nTo the lasc', 'i', 'vious pleasing of a '), 
('hamber\nTo the lasciv', 'i', 'ous pleasing of a lu'), 
('the lascivious pleas', 'i', 'ng of a lute \nBut I '), 
('sing of a lute \nBut ', 'I', ' that am not shaped '), 
('not shaped for sport', 'i', 've tricks \nNor made '), 
('aped for sportive tr', 'i', 'cks \nNor made to cou'), 
('ourt an amorous look', 'i', 'ng glass \nI that am '), 
('rous looking glass \n', 'I', ' that am rudely stam'), 
('before a wanton ambl', 'i', 'ng nymph \nI that am '), 
('nton ambling nymph \n', 'I', ' that am curtail d o'), 
('mph \nI that am curta', 'i', 'l d of this fair pro'), 
('t am curtail d of th', 'i', 's fair proportion   '), 
('curtail d of this fa', 'i', 'r proportion        '), 
('of this fair proport', 'i', 'on                  ')]

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

[('               \nNow ', 'i', 's the winter of our '), 
('       \nNow is the w', 'i', 'nter of our      dis'), 
('winter of our      d', 'i', 'scontent\nMade glorio'), 
('discontent\nMade glor', 'i', 'ous summer by this s'), 
('lorious summer by th', 'i', 's sun of York;\nAnd a'), 
("ur'd upon our house\n", 'I', 'n the         deep b'), 
('som of the ocean bur', 'i', 'ed.\nNow are our brow').......]

Заменить URL-адреса из текста другим текстом

Мы можем удалить любые ненужные URL-адреса из нашего текста и заменить его другим текстом —

Python3

from textacy import preprocessing
 
 
# Replace URLs
txt = "https://www.geeksforgeeks.org/ is the best place to learn anything"
rm_url = preprocessing.replace.urls(txt,"GeeksforGeeks")
 
print(rm_url)

Вывод:

Замените электронные письма другим

Замените электронные письма другим текстом

Python3

from textacy import preprocessing
 
# Replace Emails
mail = "Send me a mail in the following address - example@gmail.com"
rm_mail = preprocessing.replace.emails(mail,"UserMail")
 
print(rm_mail)

Вывод:

Заменить номер телефона

Python3

from textacy import preprocessing
 
# Replace phone number
num = "Call me at 12345678910"
rm_num = preprocessing.replace.phone_numbers(num,"NUM")
 
print(rm_num)

Вывод:

сли мы передадим более одного чис

Если мы передадим более одного числа, то все они будут заменены на NUM.

Python3

from textacy import preprocessing
 
# Replace phone number
num = "Call me at 12345678910 or 7896451235"
rm_num = preprocessing.replace.phone_numbers(num,"NUM")
 
print(rm_num)

Заменить любое число

Python3

from textacy import preprocessing
 
# Replace Number
n = "Any number like 12 or 86 , maybe 100 etc"
rm_n = preprocessing.replace.numbers(n,"Numbers")
 
print(rm_n)

Удалите тексты, окруженные скобками, а также квадратные скобки:

Python3

from textacy import preprocessing
 
txt = """Python was conceived in the late 1980s by Guido van Rossum at Centrum Wiskunde 
& Informatica (CWI) in the Netherlands 
as a successor to the ABC programming language, which was inspired by SETL, 
capable of exception handling (from the start plus new capabilities in Python 3.11)"""
 
print(preprocessing.remove.brackets(txt))

Вывод:

Python was conceived in the late 1980s by Guido van Rossum at Centrum Wiskunde 
& Informatica  in the Netherlands
as a successor to the ABC programming language, which was inspired by SETL,
capable of exception handling

Мы также можем передать аргумент с ключевым словом, вызываемый только, и передать список типовых скобок, которые мы хотим удалить. Он поддерживает три значения : квадратный, фигурный, круглый.

Python3

from textacy import preprocessing
 
txt = """Python was conceived in the late 1980s by Guido van Rossum at Centrum Wiskunde 
& Informatica (CWI) in the Netherlands 
as a successor to the [ABC programming language], which was inspired by SETL, 
capable of exception handling {from the start plus new capabilities in Python 3.11}"""
 
print(preprocessing.remove.brackets(txt,only=["round","square"]))

Вывод:

Python was conceived in the late 1980s by Guido van Rossum at Centrum Wiskunde 
& Informatica  in the Netherlands
as a successor to the , which was inspired by SETL,
capable of exception handling {from the start plus new capabilities in Python 3.11}

Читайте также:  Лучшие инструменты и платформы для создания сайтов
Оцените статью
bestprogrammer.ru
Добавить комментарий