【问题标题】:Remove stop words from a dataframe's colum with Python使用 Python 从数据框的列中删除停用词
【发布时间】:2020-05-04 06:06:15
【问题描述】:

我设法从网站中提取了一个单词列表并将它们存储在 dataframe 中。现在我需要从“Palabras”列中删除其中一些词,并只保留前 500 条记录。

这是我目前的代码:

import requests
wiki_url = "https://es.wiktionary.org/wiki/Wikcionario:Frecuentes-(1-1000)-Subt%C3%ADtulos_de_pel%C3%ADculas"
wiki_texto = requests.get(wiki_url).text
from bs4 import BeautifulSoup
wiki_datos = BeautifulSoup(wiki_texto, "html")
wiki_filas = wiki_datos.findAll("tr")
print(wiki_filas[1])

print("...............................")

wiki_celdas = wiki_datos.findAll("td")
print(wiki_celdas[0:])
fila_1 = wiki_celdas[0:]
info_1 = [elemento.get_text() for elemento in fila_1]
print(fila_1)
print(info_1)
info_1[0] = int(float(info_1[0]))
print(info_1)


print("...............................")

num_or = [int(float(elem.findAll("td")[0].get_text())) for elem in wiki_filas[1:]]
palabras = [elem.findAll("td")[1].get_text().rstrip() for elem in wiki_filas[1:]]
frecuencia = [elem.findAll("td")[2].get_text().rstrip() for elem in wiki_filas[1:]]
print(num_or[0:])
print(palabras[0:])
print(frecuencia[0:])

from pandas import DataFrame
tabla = DataFrame([num_or, palabras, frecuencia]).T
tabla.columns = ["Núm. orden", "Palabras", "Frecuencia"]
print(tabla.head())
print(tabla)

print("...............................")

import nltk
nltk.download()
from nltk.corpus import stopwords 
prep = stopwords.words('spanish')
print(prep)

所以我需要删除这段代码中包含的单词列表

stopwords.words('西班牙语')

来自“Palabras”列,只保留前 500 条记录(频率较高的词):

import nltk
nltk.download()
from nltk.corpus import stopwords 
prep = stopwords.words('spanish')

提前致谢!

【问题讨论】:

    标签: python dataframe web-scraping stop-words


    【解决方案1】:

    我设法从网站中提取了一个单词列表并将它们存储在 一本字典。

    注意:实际上,您将它们存储在数据框中。

    您可以使用isin。您基本上想要获取列'Palabras' 中的单词在您的停用词列表中的行。因此,您只需要过滤这些行,然后使用与使用 ~ 的行相反。既然已经排序了,就用.head(500)

    tabla = tabla[~tabla['Palabras'].isin(prep)].head(500)
    

    另外,由于 html 包含 table 标签,我会考虑使用 pandas .read_html(),因为它在后台使用了 beautifulsoup,但会为您完成艰苦的工作。您的代码可以大大减少:

    完整代码,相同结果:

    import nltk
    import pandas as pd
    #nltk.download()
    from nltk.corpus import stopwords 
    prep = stopwords.words('spanish')
    print(prep)
    
    
    
    tabla_beta = pd.read_html(wiki_url)[0]
    tabla_beta.columns = ["Núm. orden", "Palabras", "Frecuencia"]
    tabla_beta = tabla_beta[~tabla_beta['Palabras'].isin(prep)].head(500)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-08-13
      • 1970-01-01
      • 1970-01-01
      • 2021-02-02
      • 1970-01-01
      • 2021-07-04
      相关资源
      最近更新 更多