gpt4 book ai didi

python - 如何在 Python 中将 HTML 表格转换为数组

转载 作者:技术小花猫 更新时间:2023-10-29 12:38:27 25 4
gpt4 key购买 nike

我有一个 html 文档,我想从该文档中提取表格并将它们作为数组返回。我正在描绘 2 个函数,一个用于查找文档中的所有 html 表格,另一个用于将 html 表格转换为二维数组。

是这样的:

htmltables = get_tables(htmldocument)
for table in htmltables:
array=make_array(table)

有两个问题:1. 数字表每天都在变化2. 表格有各种奇怪的额外格式,如粗体和闪烁标签,随机添加。

谢谢!

最佳答案

使用BeautifulSoup (我推荐 3.0.8)。查找所有表很简单:

import BeautifulSoup

def get_tables(htmldoc):
soup = BeautifulSoup.BeautifulSoup(htmldoc)
return soup.findAll('table')

但是,在 Python 中,一个 array是一维的并且被限制为非常基本的类型作为项目(整数、 float 、that elementary)。所以没有办法在 Python array 中压缩 HTML 表格。

也许您指的是 Python list?这也是一维的,但任何东西都可以是一个项目,所以你可以有一个列表列表(每个 tr 标签一个子列表,我想,每个 td 包含一个项目标签)。

那会给出:

def makelist(table):
result = []
allrows = table.findAll('tr')
for row in allrows:
result.append([])
allcols = row.findAll('td')
for col in allcols:
thestrings = [unicode(s) for s in col.findAll(text=True)]
thetext = ''.join(thestrings)
result[-1].append(thetext)
return result

这可能还不是您想要的(不跳过 HTML 注释,子列表的项目是 unicode 字符串而不是字节字符串等)但它应该很容易调整。

关于python - 如何在 Python 中将 HTML 表格转换为数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2870667/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com