Python 为什么Dash在上传文件时会出现解析错误?
上载Excel或CSV会导致错误。我遵循了Dash演示,但一旦我尝试扩展它以进行绘图之类的操作,它就不起作用了。我不想只是展示一张桌子。Dash_Table函数已更新,因此以前使用Dash_Table_实验的示例不再有效 我花了整整一个晚上在堆栈交换上,修改代码并阅读其他解决方案。下面提供了完整的工作代码。我还想添加一个下拉回调函数,通过分类变量“过滤”数据Python 为什么Dash在上传文件时会出现解析错误?,python,plotly,plotly-dash,Python,Plotly,Plotly Dash,上载Excel或CSV会导致错误。我遵循了Dash演示,但一旦我尝试扩展它以进行绘图之类的操作,它就不起作用了。我不想只是展示一张桌子。Dash_Table函数已更新,因此以前使用Dash_Table_实验的示例不再有效 我花了整整一个晚上在堆栈交换上,修改代码并阅读其他解决方案。下面提供了完整的工作代码。我还想添加一个下拉回调函数,通过分类变量“过滤”数据 import base64 import datetime import io import plotly.graph_objs
import base64
import datetime
import io
import plotly.graph_objs as go
import dash
from dash.dependencies import Input, Output, State
import dash_core_components as dcc
import dash_html_components as html
import dash_table
import pandas as pd
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
app.layout = html.Div([
dcc.Upload(
id='upload-data',
children=html.Div([
'Drag and Drop or ',
html.A('Select Files')
]),
style={
'width': '100%',
'height': '60px',
'lineHeight': '60px',
'borderWidth': '1px',
'borderStyle': 'dashed',
'borderRadius': '5px',
'textAlign': 'center',
'margin': '10px'
},
# Allow multiple files to be uploaded
multiple=False
),
html.Div(id='output-data-upload'),
dcc.Graph(id='graph1')
])
def parse_contents(contents, filename):
content_type, content_string = contents.split(',')
decoded = base64.b64decode(content_string)
try:
if 'csv' in filename:
# Assume that the user uploaded a CSV file
df = pd.read_csv(
io.StringIO(decoded.decode('utf-8')))
elif 'xls' in filename:
# Assume that the user uploaded an excel file
df = pd.read_excel(io.BytesIO(decoded))
except Exception as e:
print(e)
return html.Div([
'There was an error processing this file.'
])
return html.Div([
html.H5(filename),
# html.H6(datetime.datetime.fromtimestamp(date)),
dash_table.DataTable(
data=df.to_dict('records'),
columns=[{'name': i, 'id': i} for i in df.columns]
),
html.Hr(), # horizontal line
# For debugging, display the raw contents provided by the web browser
html.Div('Raw Content'),
html.Pre(contents[0:200] + '...', style={
'whiteSpace': 'pre-wrap',
'wordBreak': 'break-all'
})
])
@app.callback(Output('output-data-upload', 'children'),
[Input('upload-data', 'contents')],
[State('upload-data', 'filename')])
def update_output(list_of_contents, list_of_names):
if list_of_contents is not None:
children = [
parse_contents(c, n) for c, n in
zip(list_of_contents, list_of_names)]
return children
@app.callback(
Output('graph1', 'figure'),
[Input('upload-data', 'contents'),
Input('upload-data', 'filename')])
def plot_graph(contents, filename):
df = parse_contents(contents, filename)
trace1 = go.Bar(
x=df['Quarter'],
y=df['Score'],
)
layout = go.Layout(
title='graph1'
)
fig = go.Figure(data = [trace1], layout=layout)
return fig
if __name__ == '__main__':
app.run_server(debug=True)
我得到的错误是:更新output-data-upload时回调错误。子项:ValueError:没有足够的值来解包(预期为2,得到1)
及
AttributeError:“非类型”对象没有属性“拆分”
问题似乎在于python如何处理解析器:
def parse_contents(contents, filename):
content_type, content_string = contents.split(',')
decoded = base64.b64decode(content_string)
但这些解决方案似乎都无法解决问题
请帮忙。既然这么多人都在为这个问题而挣扎(看起来是这样),如果我们能够解决它并发布一个功能代码(Github?)来完成Shiny已经很容易做到的事情,那就太好了。您的代码:
children = [
parse_contents(c, n) for c, n in
zip(list_of_contents, list_of_names)]
然后
def parse_内容(内容、文件名):
内容类型,内容字符串=contents.split(','))
decoded=base64.b64解码(内容\字符串)
...
这里,当无中的c
时发生错误,然后parse_contents
的contents
参数为None,并且发生“None没有.split”错误
如果c
不是None,而是只有一个单词,则contents.split()
只返回一个元素,并发生“没有足够的值来解包”错误
我会过滤它:
pairs=zip(内容列表、名称列表)
children=[如果c和(len(c.split('),')==2,则成对分析(c,n)的内容(c,n)]
您也可以考虑在代码之外执行拆分> PARSEOFIX内容< /代码>并更改它周围的代码。< /P> 我还将尝试记录内容错误的文件名,例如,如果不是c或len(c.split(',')!=2),则成对记录(c,n)的文件名。您的代码:
children = [
parse_contents(c, n) for c, n in
zip(list_of_contents, list_of_names)]
然后
def parse_内容(内容、文件名):
内容类型,内容字符串=contents.split(','))
decoded=base64.b64解码(内容\字符串)
...
这里,当无中的c
时发生错误,然后parse_contents
的contents
参数为None,并且发生“None没有.split”错误
如果c
不是None,而是只有一个单词,则contents.split()
只返回一个元素,并发生“没有足够的值来解包”错误
我会过滤它:
pairs=zip(内容列表、名称列表)
children=[如果c和(len(c.split('),')==2,则成对分析(c,n)的内容(c,n)]
您也可以考虑在代码之外执行拆分> PARSEOFIX内容< /代码>并更改它周围的代码。< /P>
我还将尝试记录内容错误的文件名,例如,如果不是c或len(c.split(',')!=2),则成对记录(c,n)的文件名。解决了这个问题。在此发布供其他人使用的信息:
def parse_contents(contents, filename):
if contents is not None:
content_type, content_string = contents.split(',')
decoded = base64.b64decode(content_string)
try:
if 'csv' in filename:
# Assume that the user uploaded a CSV file
df = pd.read_csv(
io.StringIO(decoded.decode('utf-8')))
elif 'xlsx' in filename:
# Assume that the user uploaded an excel file
df = pd.read_excel(io.BytesIO(decoded))
except Exception as e:
print(e)
return html.Div([
'There was an error processing this file.'
])
return df
else:
return [{}]
@app.callback(Output('table', 'data'),
[Input('upload-data', 'contents'),
Input('upload-data', 'filename')])
def update_output(contents, filename):
if contents is not None:
df = parse_contents(contents, filename)
if df is not None:
return df.to_dict('records')
else:
return [{}]
else:
return [{}]
@app.callback(
Output('graph1', 'figure'),
[Input('upload-data', 'contents'),
Input('upload-data', 'filename')])
def plot_graph(contents, filename):
df = parse_contents(contents, filename)
trace1 = go.Bar(
x=df['Quarter'],
y=df['Score'],
)
layout = go.Layout(
title='graph1'
)
fig = go.Figure(data = [trace1], layout=layout)
return fig
解决了。在此发布供其他人使用的信息:
def parse_contents(contents, filename):
if contents is not None:
content_type, content_string = contents.split(',')
decoded = base64.b64decode(content_string)
try:
if 'csv' in filename:
# Assume that the user uploaded a CSV file
df = pd.read_csv(
io.StringIO(decoded.decode('utf-8')))
elif 'xlsx' in filename:
# Assume that the user uploaded an excel file
df = pd.read_excel(io.BytesIO(decoded))
except Exception as e:
print(e)
return html.Div([
'There was an error processing this file.'
])
return df
else:
return [{}]
@app.callback(Output('table', 'data'),
[Input('upload-data', 'contents'),
Input('upload-data', 'filename')])
def update_output(contents, filename):
if contents is not None:
df = parse_contents(contents, filename)
if df is not None:
return df.to_dict('records')
else:
return [{}]
else:
return [{}]
@app.callback(
Output('graph1', 'figure'),
[Input('upload-data', 'contents'),
Input('upload-data', 'filename')])
def plot_graph(contents, filename):
df = parse_contents(contents, filename)
trace1 = go.Bar(
x=df['Quarter'],
y=df['Score'],
)
layout = go.Layout(
title='graph1'
)
fig = go.Figure(data = [trace1], layout=layout)
return fig
谢谢你的快速回复。因此,您建议:
def update\u输出(内容列表,名称列表):
如果内容列表不是无:
pairs=zip(内容列表,名称列表)
子项=[parse\u contents(c,n)for c,n in pairs if c]返回子项
,因为我尝试了这段代码,我也犯了同样的错误。我把我的答案扩展到了其他情况。谢谢。这就解决了问题。但是,结果是,我得到了一个绘图回调函数的回调错误。回调不应该识别dataframe对象中的列标题吗?共有3列:“品牌”、“季度”和“分数”def plot_graph(contents,filename):df=parse_contents(contents,filename)trace1=go.Bar(x=df['Quarter',y=df['Score']),可能与此错误有关:AttributeError:'NoneType'对象没有属性'split'。谢谢您的快速回复。因此,您建议:def update\u输出(内容列表,名称列表):
如果内容列表不是无:
pairs=zip(内容列表,名称列表)
子项=[parse\u contents(c,n)for c,n in pairs if c]返回子项
,因为我尝试了这段代码,我也犯了同样的错误。我把我的答案扩展到了其他情况。谢谢。这就解决了问题。但是,结果是,我得到了一个绘图回调函数的回调错误。回调不应该识别dataframe对象中的列标题吗?共有3列:“品牌”、“季度”和“分数”def plot_graph(contents,filename):df=parse_contents(contents,filename)trace1=go.Bar(x=df['Quarter',y=df['Score']),可能与此错误有关:AttributeError:'NoneType'对象没有属性'split'