Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 如何在python函数中转换此python代码?_Python 3.x_Function - Fatal编程技术网

Python 3.x 如何在python函数中转换此python代码?

Python 3.x 如何在python函数中转换此python代码?,python-3.x,function,Python 3.x,Function,我的脚本使用线程池。我有html表到json转换的工作代码 我使用pandas将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

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

我使用pandas将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\u 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
调用

我想您不太了解函数、参数以及如何调用函数


考虑一下阅读,这是一个简短的阅读。

你有什么问题?转换为函数时。由于我是新python,我不知道如何将其转换为函数。我不明白,您是否可以在
abcd()
函数中添加一个参数,即
def abcd(html_str):
并让它
返回结果
?我如何使用池来实现此功能?您的意思是什么?您的示例代码有一个输入字符串,您不需要池。如果您展示更多代码,并尝试解释线程的用途,那么我可以提供帮助。我希望提高执行速度,因此我希望使用多线程。您不会通过多线程来加速单个函数调用。这不是它的工作原理。同样,在python中,多线程只会真正帮助I/O绑定的任务。