【问题标题】:How to use split() with Streamlit如何在 Streamlit 中使用 split()
【发布时间】:2021-11-15 00:32:29
【问题描述】:

我有一个脚本可以打开一个文本文件,读取列表中的行,然后使用.split() 拆分行。

我想在 Streamlit 中使用相同的功能,但 split 抛出异常:

TypeError: 需要一个类似字节的对象,而不是 'str'

这是 cmets 中提到的一个最小示例:

import streamlit as st
import pandas as pd

# TIlte of the App
st.title(
"MWE")

#Side bar
st.sidebar.subheader("File Upload")

semi_colon = -5
entry_id = -4

#File upload
uploaded_log = st.sidebar.file_uploader(label="Upload your Log File",type='txt')

if uploaded_log is not None:
    print(uploaded_log)
    try:
    print("Open And readlines")
    eeprom = uploaded_log.readlines()

    print("create lists from the logfiles")
    ##create lists from the logfiles 
    sip_list = [x for x in eeprom if (x[entry_id] == ord('1') and x[semi_colon] == ord(';'))]
    slope_list = [x for x in eeprom if (x[entry_id] == ord('2') and x[semi_colon] == ord(';'))]
    cal1_list = [x for x in eeprom if (x[entry_id] == ord('3') and x[semi_colon] == ord(';'))]
    
    group_of_lists = [sip_list,slope_list,cal1_list]
    group_new = [[l.split(";") for l in group] for group in group_of_lists]

    except:
    print("Error occured")

else:
st.write('Please upload a file to the app')

【问题讨论】:

  • 你能添加一个 MWE with streamlit 不工作吗?顺便说一句,您可以更清晰地编写“列表列表”,但让我们先看看您最终想怎么做。
  • 顺便说一句,我认为你的 {first...sixth}_list 是你的 sip(etc)_list
  • the app throws an exception 是您应该提供给我们的最重要的东西。
  • @2e0byo 是的,我刚刚在问题中更改了它
  • 谢谢!请注意,这不是一个完整的 MWE。开头至少需要import streamlit,以及Except

标签: python streamlit


【解决方案1】:

感谢您的每一条评论,我想我已经找到了答案。 而不是:

 group_new = [[l.split(";") for l in group] for group in group_of_lists]

应该是:

group_new = [[str(l).split(";") for l in group] for group in group_of_lists]

原因在于这些行仍然是类似字节的对象,首先需要将它们转换为字符串才能在其上使用字符串函数。我也找到了一个关于它的社区帖子: https://discuss.streamlit.io/t/upload-text-file-which-needs-to-be-read-line-by-line/7714/2

【讨论】:

  • 感谢您添加答案以清除它
猜你喜欢
  • 2021-07-26
  • 1970-01-01
  • 2021-07-20
  • 2022-12-13
  • 2022-06-22
  • 2022-01-26
  • 2021-04-12
  • 2021-07-01
  • 2013-01-24
相关资源
最近更新 更多