Gracias al siguiente código que utiliza librerías del procesamiento del lenguaje natural, como por ejemplo el paquete de NLTK. Es posible hacer diversos cálculos sobre las palabras y oraciones más utilizadas en un texto y hacer un texto más breve, en forma de resumen.

Antes de tener este código gratis por la cara, sígueme:
🟣Instagram: https://www.instagram.com/javierfinance/
🔵Twitter: https://twitter.com/JavierFinance
import bs4 as bs
import urllib.request
import re
import nltk
import bs4
import urllib.request
import requests
from bs4 import BeautifulSoup
import urllib.request
from inscriptis import get_text
from googletrans import Translator
#scrapea articulo de wikipedia
enlace = "https://en.wikipedia.org/wiki/Python_(programming_language)"
html = urllib.request.urlopen(enlace).read().decode('utf-8')
text = get_text(html)
article_text = text
article_text = article_text.replace("[ edit ]", "")
print ("###################")
from nltk import word_tokenize,sent_tokenize
# Removing Square Brackets and Extra Spaces
article_text = re.sub(r'\[[0-9]*\]', ' ', article_text)
article_text = re.sub(r'\s+', ' ', article_text)
formatted_article_text = re.sub('[^a-zA-Z]', ' ', article_text )
formatted_article_text = re.sub(r'\s+', ' ', formatted_article_text)
#nltk.download()
#EN ESTA PARTE HACE LA TOKENIZACION
sentence_list = nltk.sent_tokenize(article_text)
#EN ESTA PARTE ENCUENTRA LA FRECUENCIA DE CADA PALABRA
stopwords = nltk.corpus.stopwords.words('english')
word_frequencies = {}
for word in nltk.word_tokenize(formatted_article_text):
if word not in stopwords:
if word not in word_frequencies.keys():
word_frequencies[word] = 1
else:
word_frequencies[word] += 1
#
maximum_frequncy = max(word_frequencies.values())
for word in word_frequencies.keys():
word_frequencies[word] = (word_frequencies[word]/maximum_frequncy)
#CALCULA LAS FRASES QUE MÁS SE REPITEN
sentence_scores = {}
for sent in sentence_list:
for word in nltk.word_tokenize(sent.lower()):
if word in word_frequencies.keys():
if len(sent.split(' ')) < 30:
if sent not in sentence_scores.keys():
sentence_scores[sent] = word_frequencies[word]
else:
sentence_scores[sent] += word_frequencies[word]
#REALIZA EL RESUMEN CON LAS MEJORES FRASES
import heapq
summary_sentences = heapq.nlargest(7, sentence_scores, key=sentence_scores.get)
summary = ' '.join(summary_sentences)
print(summary)
###
#traducir:
################
translator = Translator()
translate = translator.translate(summary, src="en", dest="es")
print(translate.text)
############################
print("Haz mi curso gratis de python: https://www.udemy.com/course/python-desde-0-para-principiantes/")
Últimas entradas de Javier Finance (ver todo)
- Inteligencia Artificial para cámaras de seguridad - noviembre 6, 2023
- Los mejores Bootcamps de Data Science (Ranking) - septiembre 27, 2023
- ¿Cómo limpiar datos con Pandas? [Código Python] - septiembre 4, 2023
Hola perdon soy nuevo con Python como ejecuto este codigo?
Desde el IDE o desde consola, debes de instalar Python 3.7
tengo un error al traducir no se si puedes ayudarme
AttributeError Traceback (most recent call last)
in ()
5 ################
6 translator = Translator()
—-> 7 translate = translator.translate(summary, src=”en”, dest=”es”)
8 print(translate.text)
9 ############################
3 frames
/usr/local/lib/python3.6/dist-packages/googletrans/gtoken.py in _update(self)
60
61 # this will be the same as python code after stripping out a reserved word ‘var’
—> 62 code = self.RE_TKK.search(r.text).group(1).replace(‘var ‘, ”)
63 # unescape special ascii characters such like a \x3d(=)
64 code = code.encode().decode(‘unicode-escape’)
AttributeError: ‘NoneType’ object has no attribute ‘group’
Hola Javier
Un gusto Saludarte. Te comento que el código de phyton de resumen texto funciona perfectamente pero cuanto llega a la linea de traslator me genera este error:
Traceback (most recent call last):
File “C:\Users\CO00000834\OneDrive – Prosegur Cia. De Seguridad, S.A\PERSONAL\Cursos\InteligenciaArtificial\CursoBasicoIAPhyton\Prueba.py”, line 72, in
translate = translator.translate(summary, src=”en”, dest=”es”)
File “C:\RoboDK\Python37\lib\site-packages\googletrans\client.py”, line 182, in translate
data = self._translate(text, dest, src, kwargs)
File “C:\RoboDK\Python37\lib\site-packages\googletrans\client.py”, line 78, in _translate
token = self.token_acquirer.do(text)
File “C:\RoboDK\Python37\lib\site-packages\googletrans\gtoken.py”, line 194, in do
self._update()
File “C:\RoboDK\Python37\lib\site-packages\googletrans\gtoken.py”, line 62, in _update
code = self.RE_TKK.search(r.text).group(1).replace(‘var ‘, ”)
AttributeError: ‘NoneType’ object has no attribute ‘group’
[Finished in 3.7s]
Sabes que puede ser?
Muchas gracias
Hola Raul,
acabo de tener el mismo problema.. mi solucion:
pip install googletrans==3.1.0a0
fuentes de lectura:
https://stackoverflow.com/questions/52455774/googletrans-stopped-working-with-error-nonetype-object-has-no-attribute-group
https://github.com/ssut/py-googletrans/pull/237
https://github.com/lushan88a/google_trans_new
un saludo