-2

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

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

在一个 jupyter 笔记本单元格中,我使用了以下代码

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')
4

1 回答 1

1

这行得通吗?

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
于 2021-09-28T10:14:06.337 回答