En este artículo, vamos a tokenizar el contenido de la oración, el párrafo y la página web utilizando el kit de herramientas NLTK en el entorno de Python, luego eliminaremos las palabras vacías y aplicaremos la lematización en el contenido de la oración, el párrafo y la página web. Finalmente, calcularemos la frecuencia de las palabras después de eliminar las palabras vacías y la lematización.
Módulos necesarios
bs4: Beautiful Soup (bs4) es una biblioteca de Python para extraer datos de archivos HTML y XML. Para instalar esta biblioteca, escriba el siguiente comando en IDE/terminal.
pip install bs4
urllib: el paquete Urllib es la biblioteca de manejo de localizadores uniformes de recursos para python. Se utiliza para obtener URL. Para instalar esta biblioteca, escriba el siguiente comando en IDE/terminal.
pip install urllib
nltk: la biblioteca NLTK es un kit de herramientas masivo para el procesamiento del lenguaje natural en Python, este módulo nos ayuda al proporcionar toda la metodología NLP. Para instalar esta biblioteca, escriba el siguiente comando en IDE/terminal.
pip install nltk
Implementación paso a paso :
Paso 1:
- Guarde los archivos frase.txt, párrafo.txt en el directorio actual.
- Abra los archivos usando el método abierto y guárdelos en operadores de archivos llamados archivo1, archivo2.
- Lea el contenido del archivo usando el método read() y almacene todo el contenido del archivo en una sola string.
- Mostrar el contenido del archivo.
- Cierre los operadores de archivos.
Python
import nltk s = input('Enter the file name which contains a sentence: ') file1 = open(s) sentence = file1.read() file1.close() p = input('Enter the file name which contains a paragraph: ') file2 = open(p) paragraph = file2.read() file2.close()
Paso 2:
- Importe urllib.request para abrir y leer el contenido de la página web.
- Desde bs4 import BeautifulSoup que nos permite extraer datos de documentos HTML.
- Usando urllib.request, haga una solicitud a ese servidor de URL en particular.
- El servidor responderá y devolverá el documento Html.
- Lee el contenido de la página web usando el método read() .
- Pase los datos de la página web a BeautifulSoap, lo que nos ayuda a organizar y formatear los datos web desordenados al corregir el HTML incorrecto y presentarnos en estructuras fácilmente transitables.
Python
import urllib.request from bs4 import BeautifulSoup url = input('Enter URL of Webpage: ') print('\n') url_request = urllib.request.Request(url) url_response = urllib.request.urlopen(url) webpage_data = url_response.read() soup = BeautifulSoup(webpage_data, 'html.parser')
Paso 3:
- Para simplificar la tarea de tokenizar, vamos a extraer solo una parte de la página HTML.
- Usando el operador BeautifulSoup , extraiga todas las etiquetas de párrafo presentes en el documento HTML.
- Soup(‘p’) devuelve una lista de elementos que contienen todas las etiquetas de párrafo presentes en la página web.
- Cree una string vacía llamada web_page_data.
- Para cada etiqueta presente en la lista, concatene el texto encerrado entre las etiquetas en la string vacía.
Python
web_page_paragraph_contents = soup('p') web_page_data = '' for para in web_page_paragraph_contents: web_page_data = web_page_data + str(para.text)
Paso 4:
- Usando re.sub() reemplace los caracteres no alfabéticos con una string vacía.
- re.sub() toma una expresión regular, una nueva string y la string de entrada como argumentos y devuelve la string modificada (reemplaza los caracteres especificados en la string de entrada con la nueva string).
- ^ – significa que coincidirá con el patrón escrito a la derecha.
- \w – #Retorna una coincidencia en cada carácter no alfabético (caracteres que NO están entre a y Z. Como “!”, “?” espacios en blanco, números, incluido el guión bajo, etc.) y \s – coincide con un espacio en blanco.
Python
from nltk.tokenize import word_tokenize import re sentence_without_punctuations = re.sub(r'[^\w\s]', '', sentence) paragraph_without_punctuations = re.sub(r'[^\w\s]', '', paragraph) web_page_paragraphs_without_punctuations = re.sub(r'[^\w\s]', '', web_page_data)
Paso 5:
- Pase la oración, el párrafo, el contenido de la página web después de eliminar los signos de puntuación y los caracteres innecesarios en word_tokenize(), que devuelve el texto, el párrafo y la string web tokenizados.
- Muestre el contenido de la oración tokenizada, el párrafo tokenizado, la string web tokenizada.
Python
sentence_after_tokenizing = word_tokenize(sentence_without_punctuations) paragraph_after_tokenizing = word_tokenize(paragraph_without_punctuations) webpage_after_tokenizing = word_tokenize(web_page_paragraphs_without_punctuations)
Paso 6:
- de nltk.corpus importar palabras vacías.
- Descargue palabras vacías usando nltk.download(‘stopwords’) .
- Guarde las palabras vacías en inglés en nltk_stop_words .
- Compare cada palabra en la oración tokenizada, el párrafo tokenizado string web tokenizada con las palabras presentes en nltk_stop_words si alguna de las palabras en nuestros datos aparece en las palabras vacías de nltk, vamos a ignorar esas palabras.
Python
from nltk.corpus import stopwords nltk.download('stopwords') nltk_stop_words = stopwords.words('english') sentence_without_stopwords = [i for i in sentence_after_tokenizing if not i.lower() in nltk_stop_words] paragraph_without_stopwords = [j for j in paragraph_after_tokenizing if not j.lower() in nltk_stop_words] webpage_without_stopwords = [k for k in webpage_after_tokenizing if not k.lower() in nltk_stop_words]
Paso 7:
- de nltk.stem.porter importar PorterStemmer.
- Haga Stemming usando nltk: eliminando el sufijo y considerando la raíz de la palabra.
- Cree tres listas vacías para almacenar palabras derivadas de oraciones, párrafos y páginas web.
- Usando stemmer.stem(), deriva cada palabra presente en la lista anterior y guárdala en listas recién creadas.
Python
from nltk.stem.porter import PorterStemmer stemmer = PorterStemmer() sentence_after_stemming= [] paragraph_after_stemming =[] webpage_after_stemming = [] #creating empty lists for storing stemmed words for word in sentence_without_stopwords: sentence_after_stemming.append(stemmer.stem(word)) for word in paragraph_without_stopwords: paragraph_after_stemming.append(stemmer.stem(word)) for word in webpage_without_stopwords: webpage_after_stemming.append(stemmer.stem(word))
Paso 8:
- A veces, después de hacer la lematización, puede resultar en palabras mal escritas porque es un problema de implementación.
- Usando el módulo TextBlob podemos encontrar las palabras correctas relevantes para una palabra mal escrita en particular.
- Para cada palabra en oración_después_de la raíz, párrafo_después_de la raíz, página_después_de la raíz, encuentre la palabra correcta para esa palabra usando el método correcto().
- Compruebe si la palabra correcta presente en las palabras vacías. Si no está presente en las palabras vacías, reemplace la palabra correcta con la palabra mal escrita.
Python
from textblob import TextBlob final_words_sentence=[] final_words_paragraph=[] final_words_webpage=[] for i in range(len(sentence_after_stemming)): final_words_sentence.append(0) present_word=sentence_after_stemming[i] b=TextBlob(sentence_after_stemming[i]) if str(b.correct()).lower() in nltk_stop_words: final_words_sentence[i]=present_word else: final_words_sentence[i]=str(b.correct()) print(final_words_sentence) print('\n') for i in range(len(paragraph_after_stemming)): final_words_paragraph.append(0) present_word = paragraph_after_stemming[i] b = TextBlob(paragraph_after_stemming[i]) if str(b.correct()).lower() in nltk_stop_words: final_words_paragraph[i] = present_word else: final_words_paragraph[i] = str(b.correct()) print(final_words_paragraph) print('\n') for i in range(len(webpage_after_stemming)): final_words_webpage.append(0) present_word = webpage_after_stemming[i] b = TextBlob(webpage_after_stemming[i]) if str(b.correct()).lower() in nltk_stop_words: final_words_webpage[i] = present_word else: final_words_webpage[i] = str(b.correct()) print(final_words_webpage) print('\n')
Paso 9:
- Usando el método Contador en el módulo Colecciones, encuentre la frecuencia de las palabras en oraciones, párrafos, página web. Python Counter es un contenedor que contendrá el conteo de cada uno de los elementos presentes en el contenedor.
- El método Counter devuelve un diccionario con un par clave-valor como {‘word’,word_count}.
Python
from collections import Counter sentence_count = Counter(final_words_sentence) paragraph_count = Counter(final_words_paragraph) webpage_count = Counter(final_words_webpage)
A continuación se muestra la implementación completa:
Python
import nltk s = input('Enter the file name which contains a sentence: ') file1 = open(s) sentence = file1.read() file1.close() p = input('Enter the file name which contains a paragraph: ') file2 = open(p) paragraph = file2.read() file2.close() import urllib.request from bs4 import BeautifulSoup url = input('Enter URL of Webpage: ') print( '\n' ) url_request = urllib.request.Request(url) url_response = urllib.request.urlopen(url) webpage_data = url_response.read() soup = BeautifulSoup(webpage_data, 'html.parser') print('<------------------------------------------Initial Contents of Sentence are-------------------------------------------> \n') print(sentence) print( '\n' ) print('<------------------------------------------Initial Contents of Paragraph are-------------------------------------------> \n') print(paragraph) print( '\n' ) print('<------------------------------------------Initial Contents of Webpage are---------------------------------------------> \n') print(soup) print( '\n' ) web_page_paragraph_contents=soup('p') web_page_data = '' for para in web_page_paragraph_contents: web_page_data = web_page_data + str(para.text) print('<------------------------------------------Contents enclosed between the paragraph tags in the web page are---------------------------------------------> \n') print(web_page_data) print('\n') from nltk.tokenize import word_tokenize import re sentence_without_punctuations = re.sub(r'[^\w\s]', '', sentence) paragraph_without_punctuations = re.sub(r'[^\w\s]', '', paragraph) web_page_paragraphs_without_punctuations = re.sub(r'[^\w\s]', '', web_page_data) print('<------------------------------------------Contents of sentence after removing punctuations---------------------------------------------> \n') print(sentence_without_punctuations) print('\n') print('<------------------------------------------Contents of paragraph after removing punctuations---------------------------------------------> \n') print(paragraph_without_punctuations) print('\n') print('<------------------------------------------Contents of webpage after removing punctuations-----------------------------------------------> \n') print(web_page_paragraphs_without_punctuations) print('\n') sentence_after_tokenizing = word_tokenize(sentence_without_punctuations) paragraph_after_tokenizing = word_tokenize(paragraph_without_punctuations) webpage_after_tokenizing = word_tokenize(web_page_paragraphs_without_punctuations) print('<------------------------------------------Contents of sentence after tokenizing----------------------------------------------> \n') print(sentence_after_tokenizing) print( '\n' ) print('<------------------ ------------------------Contents of paragraph after tokenizing---------------------------------------------> \n') print(paragraph_after_tokenizing) print( '\n' ) print('<------------------------------------------Contents of webpage after tokenizing-----------------------------------------------> \n') print(webpage_after_tokenizing) print( '\n' ) from nltk.corpus import stopwords nltk.download('stopwords') nltk_stop_words = stopwords.words('english') sentence_without_stopwords = [i for i in sentence_after_tokenizing if not i.lower() in nltk_stop_words] paragraph_without_stopwords = [j for j in paragraph_after_tokenizing if not j.lower() in nltk_stop_words] webpage_without_stopwords = [k for k in webpage_after_tokenizing if not k.lower() in nltk_stop_words] print('<------------------------------------------Contents of sentence after removing stopwords---------------------------------------------> \n') print(sentence_without_stopwords) print( '\n' ) print('<------------------------------------------Contents of paragraph after removing stopwords---------------------------------------------> \n') print(paragraph_without_stopwords) print( '\n' ) print('<------------------------------------------Contents of webpage after removing stopwords-----------------------------------------------> \n') print(webpage_without_stopwords) print( '\n' ) from nltk.stem.porter import PorterStemmer stemmer = PorterStemmer() sentence_after_stemming = [] paragraph_after_stemming = [] webpage_after_stemming = [] #creating empty lists for storing stemmed words for word in sentence_without_stopwords: sentence_after_stemming.append(stemmer.stem(word)) for word in paragraph_without_stopwords: paragraph_after_stemming.append(stemmer.stem(word)) for word in webpage_without_stopwords: webpage_after_stemming.append(stemmer.stem(word)) print('<------------------------------------------Contents of sentence after doing stemming---------------------------------------------> \n') print(sentence_after_stemming) print( '\n' ) print('<------------------------------------------Contents of paragraph after doing stemming---------------------------------------------> \n') print(paragraph_after_stemming) print( '\n' ) print('<------------------------------------------Contents of webpage after doing stemming-----------------------------------------------> \n') print(webpage_after_stemming) print( '\n' ) from textblob import TextBlob final_words_sentence=[] final_words_paragraph=[] final_words_webpage=[] for i in range(len(sentence_after_stemming)): final_words_sentence.append(0) present_word=sentence_after_stemming[i] b=TextBlob(sentence_after_stemming[i]) if str(b.correct()).lower() in nltk_stop_words: final_words_sentence[i]=present_word else: final_words_sentence[i]=str(b.correct()) print('<------------------------------------------Contents of sentence after correcting mispelled words-----------------------------------------------> \n') print(final_words_sentence) print('\n') for i in range(len(paragraph_after_stemming)): final_words_paragraph.append(0) present_word = paragraph_after_stemming[i] b = TextBlob(paragraph_after_stemming[i]) if str(b.correct()).lower() in nltk_stop_words: final_words_paragraph[i] = present_word else: final_words_paragraph[i] = str(b.correct()) print('<------------------------------------------Contents of paragraph after correcting mispelled words-----------------------------------------------> \n') print(final_words_paragraph) print('\n') for i in range(len(webpage_after_stemming)): final_words_webpage.append(0) present_word = webpage_after_stemming[i] b = TextBlob(webpage_after_stemming[i]) if str(b.correct()).lower() in nltk_stop_words: final_words_webpage[i] = present_word else: final_words_webpage[i] = str(b.correct()) print('<------------------------------------------Contents of webpage after correcting mispelled words-----------------------------------------------> \n') print(final_words_webpage) print('\n') from collections import Counter sentence_count = Counter(final_words_sentence) paragraph_count = Counter(final_words_paragraph) webpage_count = Counter(final_words_webpage) print('<------------------------------------------Frequency of words in sentence ---------------------------------------------> \n') print(sentence_count) print( '\n' ) print('<------------------------------------------Frequency of words in paragraph ---------------------------------------------> \n') print(paragraph_count) print( '\n' ) print('<------------------------------------------Frequency of words in webpage -----------------------------------------------> \n') print(webpage_count)
Producción:
Publicación traducida automáticamente
Artículo escrito por vinayedula y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA