簡體   English   中英

有什么方法可以將 yaml 文件(以 streamlit 上傳)轉換為 python 字典?

[英]Is there any way to convert yaml file (uploaded in streamlit) into python dictionary?

我正在開發 streamlit 應用程序,我必須通過 streamlit.sidebar.file_uploader() 上傳一些 yaml 配置文件,並能夠訪問存儲在文件中的參數。

import streamlit as st
import yaml

config = st.sidebar.file_uploader("Upload config file")

if config is not None:

  with open(config, 'r') as uploaded_config:
    loaded_config = yaml.safe_load(uploaded_config)

  st.write(loaded_config['scoring'])

但是,當我嘗試將上傳的 yaml 文件作為 dict 讀取時,它會返回錯誤:

TypeError: expected str, bytes or os.PathLike object, not UploadedFile
Traceback:
File "/Users/user/opt/anaconda3/envs/npextension_app_env/lib/python3.8/site- 
packages/streamlit/scriptrunner/script_runner.py", line 557, in _run_script
exec(code, module.__dict__)
File "app.py", line 8, in <module>
with open(config, 'r') as uploaded_config:

如果我使用 .getvalue() 來獲取字節文件而不是像這樣的 UploadedFile:

import streamlit as st
import yaml

config = st.sidebar.file_uploader("Upload config file")

if config is not None:

  with open(config.getvalue(), 'r') as uploaded_config:
    loaded_config = yaml.safe_load(uploaded_config)

  st.write(loaded_config['scoring'])

它返回另一個錯誤:

OSError: [Errno 63] File name too long: b'features_list:\n - NO2 Mean\n - 03 Mean\n - 
SO2 Mean\n - is_weekend\n\nevents_list:\n - is_xmas\n\nds: Date Local\n\ny: CO Mean\n\nscoring: mae\n\nfreq: D\n\ntest_p: 
0.06\n\nvalid_p: 0.1\n\nk: 3\n'
Traceback:
File "/Users/user/opt/anaconda3/envs/npextension_app_env/lib/python3.8/site- 
packages/streamlit/scriptrunner/script_runner.py", line 557, in _run_script
exec(code, module.__dict__)
File "app.py", line 8, in <module>
with open(config.getvalue(), 'r') as uploaded_config:

我的 yaml 文件如下所示:

features_list:
  - NO2 Mean
  - 03 Mean
  - SO2 Mean
  - is_weekend
events_list:
  - is_xmas
ds: Date Local
y: CO Mean
scoring: mae
freq: D
test_p: 0.06
valid_p: 0.1
k: 3
import yaml

with open("/home/ubuntu/data.yaml", 'r') as stream:
    try:
        parsed_yaml=yaml.safe_load(stream)
        print(parsed_yaml)
    except yaml.YAMLError as exc:
        print(exc)

我在https://fedingo.com/how-to-read-yaml-file-to-dict-in-python/上找到了此代碼

所以,我發現了錯誤。 而不是使用:

with open(config, 'r') as uploaded_config:
 loaded_config = yaml.safe_load(uploaded_config)

用這個:

loaded_config = yaml.safe_load(config)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM