我如何在 python 函数中转换这个 python 代码?

阿马尔萨加特

我在我的脚本中使用线程池。我有将 html 表转换为 json 的工作代码。

我正在使用熊猫将 html 表转换为 json。

html_source2 = str(html_source1)

pool = ThreadPool(4) 

table = pd.read_html(html_source2)[0]
table= table.loc[:,~table.columns.str.startswith('Unnamed')]
d = (table.to_dict('records'))
print(json.dumps(d,ensure_ascii=False))
results = (json.dumps(d,ensure_ascii=False))

我想要这样的东西:

html_source2 = str(html_source1)

pool = ThreadPool(4) 

def abcd():
  table = pd.read_html(html_source2)[0]
  table= table.loc[:,~table.columns.str.startswith('Unnamed')]
  d = (table.to_dict('records'))
  print(json.dumps(d,ensure_ascii=False))
  results = (json.dumps(d,ensure_ascii=False))
平谷

你快到了。你需要让函数在这里接受一个输入参数,html_str然后让它返回你需要的结果,这样你就可以在函数外使用它们。

html_source2 = str(html_source1)

pool = ThreadPool(4) 

def abcd(html_str):
    table = pd.read_html(html_str)[0]
    table= table.loc[:,~table.columns.str.startswith('Unnamed')]
    d = (table.to_dict('records'))
    print(json.dumps(d,ensure_ascii=False))
    results = (json.dumps(d,ensure_ascii=False))
    return results 

my_results = abcd(html_source2)

print如果不需要查看函数中的输出,则删除调用

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章