You don't have access to this class

Keep learning! Join and start boosting your career

Aprovecha el precio especial y haz tu profesión a prueba de IA

Antes: $249

Currency
$209
Suscríbete

Termina en:

1 Días
7 Hrs
8 Min
4 Seg

Estadísticas básicas del lenguaje

7/24
Resources

How to use statistics in natural language processing?

Natural language processing (NLP) is a fascinating field that combines computer science, artificial intelligence and computational linguistics to understand and interpret human language. A key element in this process is the use of statistics to analyze text and extract valuable information. In this article, we will delve into how statistical tools are applied in NLP to enrich our understanding of language.

What tools and libraries are essential for statistical analysis in text?

For effective statistical analysis in NLP using Python, several crucial libraries and tools are needed. Here are some of the most prominent ones:

  • NLTK (Natural Language Toolkit): one of the most widely used libraries for working with natural language in Python. It provides tools for tokenization, tagging, text analysis and more.

  • Matplotlib: This is a Python data visualization library that is very useful for presenting graphs and distributions.

  • NumPy: A fundamental library when working with linear algebra and advanced mathematics in Python. It is essential for efficient handling of matrices and vectors. There are courses dedicated to deepen its use.

In addition, it is common to work with pre-existing datasets, such as the NLTK books dataset, which contains tokenized books in English, being one of the most useful for text processing.

How to start tokenizing and calculating text metrics?

When working with text, a critical initial step is tokenization, i.e., breaking the text into individual words or tokens. Once tokenized, useful metrics can be calculated that provide us with information about the text, such as text length and lexical richness.

  • Tokenization: With NLTK, you can easily import datasets and start tokenizing. For example, using from nltk import book and then querying the specific tokens for a text.
from nltk.book import *tokens = text1[:10] # Get first 10 tokens
  • Length and lexical richness: Text length refers to the total number of tokens, while lexical richness is defined as the number of unique words divided by the total number of words.
text_length = len(text1)vocabulary = set(text1)lexical_richness = len(vocabulary) / text_length

How to define functions useful for text analysis?

Defining functions in Python facilitates code reuse and allows you to calculate metrics such as lexical richness and percentage of word usage. Let's see how to define some useful functions:

  • Function to calculate lexical richness:
def lexical_richness(text): vocabulary = set(text) return len(vocabulary) / len(text).

This function helps us to calculate how diverse the vocabulary of the text is.

  • Function to calculate the percentage of a word:
def percentage_word(word, text): return 100 * text.count(word) / len(text).

Using this function, we can determine how common a particular word is within a text, expressed as a percentage.

In conclusion, the use of statistical tools in NLP is essential for the analysis and deep understanding of texts. These techniques allow us to unravel language patterns and make interpretations that otherwise would not be possible. With practice and curiosity, you will be able to take full advantage of these tools and functions for your future projects in natural language processing.

Contributions 28

Questions 3

Sort by:

Want to see more contributions, questions and answers from the community?

Una aclaración, cuando se define la función riqueza_lexica(texto), la variable vocabulario esta mal definida deberia ser :
vocabulario=sorted(set(texto)) y no así text1

Les comparto una forma en la que pueden ver la riqueza lexica de todos los textos del modulo nltk.book

def lexical_affluence(corpus):
    vocabulary = sorted(set(corpus))
    return len(vocabulary) / len(corpus)

texts = [ i for i in dir(nltk.book) if re.search(r'text\d', i)]
for text in texts:
    exec(compile(f'print({text}.name, "\\n", lexical_affluence({text}), "\\n" )', 
        '', 'exec'))

Esto fue lo que se me ocurrio a mi para poder pasar los el nombre los textos como un parametro, si saben otra forma me gustaria saberlo c:

Que buen curso y que excelente profesor.Algo que parece tan complejo, lo presenta de una forma simple.
Una pregunta :Cual es el procedimiento a seguir si tengo un texto que quiero analizar y no esta en la librería de nltk?

  • Primer paso

    Importar las librerías necesarias; NLTK tiene un paquete. de libros llamado "book" asi que debemos descargarlo

    import nltk
    nltk.download('book')
    from nltk.book import *
    import matplotlib.pyplot as plt
    import numpy as np
    

    Se puede escoger entre varios libros con text y el numero , ejemplo text3

    • También podemos ver los tks con text3.tokens[:10]
  • Riqueza lexica

    R1 = total de palabras unicas/ total de palabras = longitud del vocabulario/longitud del texto

    • Vocabulario = Palabras únicas de un texto
    vocabulario = sorted(**set**(text3))
    print(vocabulario[1000:1050])
    
    • set = es una funcion que toma la lista de tks repetidos y los deja una sola vez

    • Riqueza léxica para un libro

      rl = len(vocabulario)/len(text3)
      print(rl)
      
    • Riqueza lexica general

      Podemos general una función para hallar la rl de cualquier libro del dataset

      def riqueza_lexica (texto):
          vocabulario = sorted(set(texto))
          return len(vocabulario)/len(texto)
      
      riqueza_lexica(text3)
      
    • porcentaje por palabras

      def porcentaje_palabra (palabra,texto):
          return 100*texto.count(palabra)/len(texto)
      
      porcentaje_palabra('lord',text3)
      

Cúal seria una forma eficiente de escribir una función en python en el que solo debamos poner el texto (ya sea text6,text4,etc) y que no tengamos que definir el vocabulario de cada uno?
Nose si me estoy explicando correctamente, me refiero a esta parte

vocabulario = sorted(set(text7))

Algo que entendí en el link sobre el objeto “set” es útil para poder eliminar datos duplicados.

La version actualizada del link de la documentacion de Set es https://docs.python.org/2/library/stdtypes.html#set

Comparto la función que escribí para recorrer la riqueza léxico de los 9 textos que hay: ```js def riqueza_lexica(texts): riquezas = [] num_lib = 0 for text in texts: riqueza = len(vocabulario)/len(text) riquezas.append(f"Riqueza Libro {num_lib}: {riqueza}") num_lib+=1 return riquezas texts = [text1, text2, text3, text4, text5, text6, text7, text8, text9] print(riqueza_lexica(texts)) ```def riqueza\_lexica(texts):  riquezas = \[]  num\_lib = 0  for text in texts:     riqueza = len(vocabulario)/len(text)    riquezas.append(f"Riqueza Libro {num\_lib}: {riqueza}")    num\_lib+=1  return riquezas   texts = \[text1, text2, text3, text4, text5, text6, text7, text8, text9]  print(riqueza\_lexica(texts))

La clase es muy similar a este pdf … muy similar

.tsc.uc3m.es/~miguel/MLG/adjuntos/NLTK.pdf

Algo que note es la funcion count no hace distincion entre mayusculas y minusculas para solucionar esto lo hice de dos maneras

Usando Regex

search_word = 'tHe'
search = re.compile(search_word, flags=re.IGNORECASE)
count = 0

for word in text1:
    if search.fullmatch(word, 0):
        count += 1

Usando sets

def transform(word):
    return { 
        word,
        word.lower(),
        word.upper(),
        word.capitalize()
    }

search_word = 'tHe'
count = 0

for word in transform(search_word):
    count += text1.count(word)

Aunque usando Sets tiene un mejor rendimiento

Al trabajar con estadísticas básicas del lenguaje, es importante considerar el **preprocesamiento** adecuado del texto, como la eliminación de puntuación, conversión a minúsculas y eliminación de palabras vacías (stopwords), dependiendo de los objetivos de tu análisis
Faltó normalizar los tokens de los textos a minúsculas. Dejo una captura de resultado que obtuve con la palabra moby para el texto 1 ![](https://static.platzi.com/media/user_upload/image-01739e57-2475-4e0a-80e9-f9def67502fc.jpg)

Estadisticas de los textos

Manejo de la Función Set en Python

Creo que para darle más valor a la métrica de riqueza sería pasar todas las strings a lower para que no nos tome una misma palabra como distinta.

Hola amigos
En el siguiente enlace encontraran algunos cheetset que nos podrían ayudar.

https://www.kaggle.com/getting-started/159664

les comparto otra forma de hacerlo con el tokenizador de nltk

<from nltk.tokenize import sent_tokenize, word_tokenize
#Funcion de Riqueza
def riqueza(texto):
  vocabulario=set(word_tokenize(texto))
  return len(vocabulario)/len(texto)
print(riqueza(data))
> 

Para las funciones definidas sería importante eliminar los conectores antes de sacar los indicadores de riqueza lexica o porcentaje de la palabra, pues palabras como preposiciones o artículos no le agregan valor al contenido del texto. Igualmente con el código sorted(set(text1)) se incluyen los signos de puntuación. Por eso la palabra “monster” tiene un porcentaje tan bajo. Si hacemos el ejercicio con la pabra “THE” registra una utilización del 5,26%, o si lo hacemos con “,” este representaría un 7,17%.

Les dejo la riqueza léxica de cada texto:

for text in [text1, text2, text3, text4, text5, text6, text7, text8, text9]:
  print (f'{text.name}. Riqueza léxica: {round(riquiza_lexica(text)*100, 2)}%')

Output:
Moby Dick by Herman Melville 1851. Riqueza léxica: 7.41%
Sense and Sensibility by Jane Austen 1811. Riqueza léxica: 4.83%
The Book of Genesis. Riqueza léxica: 6.23%
Inaugural Address Corpus. Riqueza léxica: 6.62%
Chat Corpus. Riqueza léxica: 13.48%
Monty Python and the Holy Grail. Riqueza léxica: 12.77%
Wall Street Journal. Riqueza léxica: 12.32%
Personals Corpus. Riqueza léxica: 22.77%
The Man Who Was Thursday by G . K . Chesterton 1908. Riqueza léxica: 9.83%

Las dos funciones que hemos aprendido en la clase:

def calculate_lexical_enrichment(text):
  vocab = sorted(set(text))               # Exclude all duplicated words from the dictionary
  return len(vocab) / len(text)           # and divide the amount of unique words per total amount of words
def word_occurrences_in_text(word, text):
  occurrences = text.count(word)          # Count the amount of repeated words in text
  return 100 * (occurrences / len(text))  # then divide per amount of words and finally multiply per 
                                          # 100 to get the percentual value.

también se puede determinar la cantidad de palabras únicas (exactamente el mismo resultado) utilizando la siguiente linea de comando (vocab ya es una variable interna del cada objeto texto)

< vocabulario = sorted(text1.vocab()) 
rl = len(vocabulario)/ len(text1)
print(rl)
>

Saludos!

Curso muy interesante, el profesor explica de manera clara.

Muy bueno este curso estoy aprendiendo bastante 😃

excelente clase, las ganas de aprender, llegan hasta altas horas de la noche.

les dejo un código parecido, pero alternativo que arroja los mismos resultados

<
import nltk
nltk.download('book')
from nltk.book import *

def lexical_wealth(text_):
  """
  this function compute the lexical wealth of a text
  input --> text_: Text object
  output --> float
  """
  vocabulary = sorted(text_.vocab())
  return len(vocabulary)/len(text_)

def word_percentage(word,text_):
  """
  this function computes the percentage that a selected word is ocuppied into a text
  input --> word: str object
        --> text_: Text object
  output --> float
  """
  vocabulary = text_.vocab()
  count = vocabulary[word]
  return 100*count/len(text_)

lexical_wealth(text1)
print(word_percentage('monster', text1))
>

¡Saludos!

Les dejo un código para calcular la riqueza léxica usando numpy 😃

tokens_np = np.array(text1.tokens)
t_palasbras_unicas = np.unique(tokens_np).size
t_palabras = tokens_np.size
t_palasbras_unicas/t_palabras
Riqueza Lexica texto 2: 0.04826383002768831
Riqueza Lexica texto 3: 0.06230453042623537
Riqueza Lexica texto 4: 0.06617622515804722
Riqueza Lexica texto 5: 0.13477005109975562
Riqueza Lexica texto 6: 0.1276595744680851

set o Conjunto
Los conjuntos se utilizan para almacenar varios elementos en una sola variable.

Set es uno de los 4 tipos de datos integrados en Python que se utilizan para almacenar colecciones de datos, los otros 3 son List, Tuple y Dictionary, todos con diferentes calidades y usos.

Un conjunto es una colección que está desordenada y no indexada.

Los conjuntos se escriben con llaves.