【问题标题】:Create a DataFrame in Python from BeautifulSoup extract从 BeautifulSoup 提取物在 Python 中创建一个 DataFrame
【发布时间】:2021-01-26 06:22:05
【问题描述】:

我可以使用 BeautifulSoup 从网络中提取数据,即单词列表。数据收集在组件 synonyms[i].text 中。但是,当我想将提取的数据转换为数据框时,我会将单词拆分为字母而不是完整的单词。如何将数据转换为正确数据框中的正确单词列表,即,像“分析”这样的单词在数据框中作为“分析”而不是拆分为“a”、“n”、“a”, 'l','y','s','e' ?

import requests
from bs4 import BeautifulSoup
import pandas as pd
page = requests.get("https://www.wordhippo.com/what-is/another-word-for/guard.html")
soup = BeautifulSoup(page.content, 'html.parser')


keyword = "guard"

synonyms = soup.select('.relatedwords')
for i in range(0, 1):
              print ('synonyms section ' + str(i + 1))
              print pd.DataFrame((list(synonyms[i].text)))

#Output that I need to convert into a DataFrame
synonyms section 1

fighter
trooper
warrior
serviceman

#The Output I am getting in the list

提前致谢。

【问题讨论】:

  • 请从intro tour 重复on topichow to ask。 “告诉我如何解决这个编码问题?”与 Stack Overflow 无关。您必须诚实地尝试解决方案,然后就您的实施提出具体问题。
  • 您还需要说明您的问题。为初学者显示输入和所需的输出。没有理由让requestsBeautifulSoup 参与您的帖子,因为它们不是您问题的一部分。只需硬编码“同义词”的示例列表,然后从那里提出您的问题。
  • @Prune。我正在使用 beautifulsoup 提取数据。但如果这样更容易,我会添加一个硬编码列表。感谢您帮助我解决问题。
  • @Prune。我已经进一步更新了我的问题。感谢您帮助我提出问题。
  • 我投票支持重新打开,因为答案已被编辑/改进。

标签: python pandas list dataframe


【解决方案1】:

我认为您需要先删除和最后删除\n,然后拆分单词列表:

for i in range(0, 1):
    print ('synonyms section ' + str(i + 1))
    print (pd.DataFrame({'text': synonyms[i].text.strip().split()}))
    
          text
0     guardian
1    custodian
2       warden
3       keeper
4       sentry
..         ...
211    soldier
212       park
213     ranger
214       more
215          ❯

[216 rows x 1 columns]

如果需要 DataFrame 的所有值,请使用 extend 方法将列表添加到 L 列表,然后在循环外调用 DataFrame 构造函数:

L = []
for i, syno in enumerate(synonyms):
    print ('synonyms section ' + str(i + 1))
    L.extend(syno.text.strip().split())

df = pd.DataFrame({'text':L})
print(df)
           text
0      guardian
1     custodian
2        warden
3        keeper
4        sentry
        ...
7667  Languages
7668          g
7669         gu
7670        gua
7671       guar

[7672 rows x 1 columns]

【讨论】:

  • 非常感谢@jezrael!这解决了我的问题。
【解决方案2】:

将单词保留在列表中。

syno_list = list()
for i, syno in enumerate(synonyms):
    print ('synonyms section ' + str(i + 1))
    word_list = syno.text.strip().split()
    syno_list.append(word_list)
    print(word_list)

【讨论】:

  • 感谢您在 @Ferris 上帮助我。
猜你喜欢
  • 2012-11-04
  • 2018-08-01
  • 1970-01-01
  • 2020-12-28
  • 2021-04-28
  • 1970-01-01
  • 1970-01-01
  • 2019-02-28
  • 1970-01-01
相关资源
最近更新 更多