将控制台输出导出到 jupyter notebook 中的 excel sheet

Export console output to excel sheet in jupyter notebook

我有一个 python 代码,其中包含一些打印语句,输出看起来像所示的层次结构。有没有办法将 jupyter book 中打印的内容原样导出到 excel 工作表?

我尝试了 python 列表 首先我把 myList = [] 然后放在迭代循环中,在每个打印语句之前,我将输出附加到 myList 就像 myList.append('Any thing')

在 jupyter notebook 单元格中,我使用了以下代码

import pandas as pd

df = pd.DataFrame() 
df["My Output"] = myList
writer = pd.ExcelWriter("Result.xlsx", engine='xlsxwriter')
df.to_excel(writer, sheet_name='Sheet1')
writer.save()

但输出只有一列..输出中有空格和制表符

看起来像那样

* ag
    + bb
        - yy
        - nn
        - oo
        - ss
    + ccc
        - tt
    + ddd
* ah
    + eee
        - ppp
        - olp
        - ws
        - ort
    + fff
        - kpr
    + ggg
    

至于我期望的输出是得到三列(每个符号一列)所以星号 * 将在一列中,加号在另一列中,减号在另一列中

我制作这段代码是为了说明目的,以便了解 myList 的样子

myList = []

myList.append('*' + 'ag')
print('*' + 'ag')

myList.append('\t+' + 'bb')
print('\t+' + 'bb')

myList.append('\t\t-' + 'yy')
print('\t\t-' + 'yy')

myList.append('\t\t-' + 'nn')
print('\t\t-' + 'nn')

myList.append('\t\t-' + 'oo')
print('\t\t-' + 'oo')

myList.append('\t\t-' + 'ss')
print('\t\t-' + 'ss')

myList.append('\t+' + 'ccc')
print('\t+' + 'ccc')

myList.append('\t\t-' + 'tt')
print('\t\t-' + 'tt')

myList.append('\t+' + 'ddd')
print('\t+' + 'ddd')

myList.append('*' + 'ah')
print('*' + 'ah')

myList.append('\t+' + 'eee')
print('\t+' + 'eee')

myList.append('\t\t-' + 'pp')
print('\t\t-' + 'pp')

myList.append('\t\t-' + 'olp')
print('\t\t-' + 'olp')

myList.append('\t\t-' + 'ws')
print('\t\t-' + 'ws')

myList.append('\t\t-' + 'ort')
print('\t\t-' + 'ort')

myList.append('\t+' + 'fff')
print('\t+' + 'fff')

myList.append('\t\t-' + 'kpr')
print('\t\t-' + 'kpr')

myList.append('\t+' + 'ggg')
print('\t+' + 'ggg')

这个有用吗?

import re

newlist = []

for string in mylist:
    row = re.findall(r'\t', string)    #get a list of all the '\t' characters
    value = re.search(r'\S+', string).group()   #extract the value eg. '+bb'
    row.append(value)    #append the value on to the end of the row.
    for x in range(3-len(row):
        row.append('\t')    #right pad the list with '\t' so all rows have length 3
    newlist.append(row)    #append the new row (eg. ['\t', '+bb', '\t'] to the list)

df = pd.DataFrame(newlist)    #create a dataframe.
df = df.replace('\t', '')    #replace '\t' characters with empty strings