No tienes acceso a esta clase

¡Continúa aprendiendo! Únete y comienza a potenciar tu carrera

Usando código estructurado: Funciones externas

23/24
Recursos

Aportes 13

Preguntas 2

Ordenar por:

¿Quieres ver más aportes, preguntas y respuestas de la comunidad?

o inicia sesión.

Le hice una pequeña modificación a la función freq_words usando el script html2text como alternativa al uso de BeautifulSoup, ya que me parece que tiene mejores resultados.

import nltk, re 
nltk.download('punkt')
from urllib import request
from nltk import word_tokenize

def install(html2text): #Aunque no es buena práctica instalar desde el archivo, funciona con la librería subprocess 
    subprocess.check_call([sys.executable, "-m", "pip", "install", html2text])

#!pip install html2text  #Esta es la forma de instalar el script desde el entorno de ejecución de Colab
import html2text


# la funcion la podemos definir en el notebook y usar directamente
def freq_words(url, n, encoding = 'utf8'):
  req = request.urlopen(url)
  html = req.read().decode(encoding)
  text = html2text.html2text(html)
  tokens = re.findall('\w+', text)
  tokens = [t.lower() for t in tokens]
  fd = nltk.FreqDist(tokens)
  return [t for (t, _) in fd.most_common(n)]

Le agregue tambien que eliminara los signos de puntuacion y los stopwords, ya que sin eso los primeros 20 que tienen mas frecuencia son signos de puntuacion y stopwords.

from urllib import request
import re
from bs4 import BeautifulSoup
import nltk
from nltk import word_tokenize
from string import punctuation
from nltk.corpus import stopwords

def get_text(file):
  #Read text from file...
  text = open(file).read()
  text = re.sub(r'<.*?', ' ', text)
  text = re.sub(r'\s+', ' ', text)
  return text

def freq_words(url, n):
  req = request.urlopen(url)
  html = req.read().decode('utf8')
  raw = BeautifulSoup(html, 'html.parser')
  stop_words = stopwords.words('english')
  text = raw.get_text()
  tokens = word_tokenize(text)
  tokens = [token.lower() for token in tokens]
  tokens = [token for token in tokens if token not in punctuation]
  tokens = [token for token in tokens if token not in stop_words]
  fd = nltk.FreqDist(tokens)
  return [t for (t, _) in fd.most_common(n)]

El signo de exclamación «!» en nuestro entorno de ejecución en Colab nos permite ejecutar comandos Bash como si lo hiciéramos desde nuestra línea de comandos local (o consola). Basta con añadir «!» delante de comando que queremos ejecutar en Colab. Dos ejemplos:

!git clone     #traernos nuestro proyecto desde GitHub a nuestro entorno de Google Colab 
!pip install    #Si necesitamos instalar con el gestor de paquetes pip de Python alguna librería que no venga preinstalada en Colab

Al hacer el ejercicio me encontré con varios problemas:

  1. Es necesario importar word_tokenize de nltk
  2. También se debe descargar el recurso ‘punkt’
  3. Cuando hacía cambios en el archivo que contenía el módulo, al volver a correr el import seguía teniendo errores porque realmente no se estaba actualizando la dependencia, como si quedara en algún tipo de caché. Para obligar a que cargara de nuevo fue necesario usar el siguiente código:
from importlib import reload
reload(freq_words)

Espero que pueda ayudar a algunos que estén varados

![](

Tengo un tutorial que escribi en otro curso respecto a los python Magics, ojala les apoye en su formación

https://platzi.com/tutoriales/1794-pandas/6960-ipython-magics-commands/

Muy buena estas dos clases.
Me ayuda un monton!

from urllib import request
from bs4 import BeautifulSoup

def freq_words(url, n, threshold):
  req = request.urlopen(url)
  html = req.read().decode('utf8')
  raw = BeautifulSoup(html, 'html.parser')
  text = raw.get_text()
  text = re.sub(r'<.*?>', ' ', text)
  text = re.sub(r'\s+', ' ', text)
  text = re.sub(r'function', ' ', text)
  text = re.sub(r'return', ' ', text)
  text = re.sub(r'target', ' ', text)
  text = re.sub(r'class', ' ', text)
  text = re.sub(r'sas_*', ' ', text)
  tokens = word_tokenize(text)
  tokens = [t.lower() for t in tokens if len(t) > threshold]
  fd = nltk.FreqDist(tokens)
  return [t for (t, _) in fd.most_common(n)]```

Wow genial, no conocía esta forma de trabajar con Google Collab!

Les dejo el codigo para usar si tienen que eliminar alguna libreria que hayan agregado por error

sys.path.remove('ruta de libreria a remover')

Espero les sirva

Estuvo muy genial este forma de trabajar en colab, al menos a mi me será muy funcional esta clase.
Gracias Francisco y Saludos!

para los que usan Jupyter Notebook este es el codigo para crear archivos

!type nul >read.py
import nltk
from nltk import word_tokenize
from urllib import request
from bs4 import BeautifulSoup
nltk.download("punkt")
def freq_words(url, n, threshold):
	req = request.urlopen(url)
	html = req.read().decode('utf8')
	raw = BeautifulSoup(html, 'html.parser')
	text = raw.get_text()
	text = re.sub(r'<.*?>', ' ', text)
	text = re.sub(r'\s+', ' ', text)
	text = re.sub(r'function', ' ', text)
	text = re.sub(r'return', ' ', text)
	text = re.sub(r'target', ' ', text)
	text = re.sub(r'class', ' ', text)
	text = re.sub(r'sas_*', ' ', text)
	tokens = word_tokenize(text)
	tokens = [t.lower() for t in tokens if len(t) > 		threshold]
	fd = nltk.FreqDist(tokens)
	return [t for (t, _) in fd.most_common(n)]