【问题标题】:Parsing text in columns解析列中的文本
【发布时间】:2020-02-06 18:49:30
【问题描述】:

我已经编写了一个代码来解析我的 html 的一部分,请参见下面的代码。我保存为 html 的最终结果,例如在 Dropbox (https://www.dropbox.com/s/kbnal2pefih2ru4/test.html?dl=0) 中的用途。 但我的问题是如何进一步编辑我的代码,以便我可以在一列中打印强部分(粗体文本),在下一列中打印普通文本。

import textwrap
import os
from bs4 import BeautifulSoup

directory ='C:/Research syntheses - Meta analysis/SeekingAlpha/Tests/'
for filename in os.listdir(directory):
    if filename.endswith('.html'):
        fname = os.path.join(directory,filename)
        with open(fname, 'r') as f:
            soup = BeautifulSoup(f.read(),'html.parser')
            participants = soup.find('div',class_='content_part hid', id='article_qanda')
        print(filename, participants)

所以我的最终结果在 csv 格式中看起来像这样:Example

【问题讨论】:

  • 基于您的 html 文件 -

    Scott Henry

    ,你应该定位 标签来过滤掉你的第 1 列,然后是第 2 列的 标签之后的后续标签
  • @atinjanki 谢谢你,我在 python 方面没有这么丰富的经验,所以我怎么能实现这个建议?

标签: python html pandas beautifulsoup


【解决方案1】:

我们可以使用 pandas 数据框将其制成您想要的表格格式。我们可以假设每个其他 p 都包含一个强项吗?如果是这样,这应该有效:

strong = []
not_strong = []

all = soup.find_all('p')
for i in range(0,len(all),2):   # loop every other
    strong.append(all[i])
    strong.append(all[i+1])

d = {'column 1': strong, 'column 2': not_strong}

df = pd.DataFrame(d)

然后它应该以您想要的格式打印。如果我们不能做出这个假设,我们必须确定每个 p 是否包含一个 strong 然后将其和下一个 p 附加到适当的列表中。

【讨论】:

  • no not always, 例如在 html 示例的开头,您可以看到一个接一个的双重强项。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-21
  • 2017-07-15
  • 1970-01-01
  • 2021-09-20
  • 1970-01-01
相关资源
最近更新 更多