【问题标题】:Export console output to excel sheet in jupyter notebook将控制台输出导出到 jupyter notebook 中的 excel 工作表
【发布时间】:2021-09-26 21:38:45
【问题描述】:

我有一个包含一些打印语句的 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')

【问题讨论】:

  • @QHarr 这个话题有什么帮助吗?
  • @MaxU 这个话题有什么帮助吗?

标签: python python-3.x pandas jupyter


【解决方案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

【讨论】:

  • 非常感谢。我得到的数据框只有符号,这些符号旁边没有数据。
  • 抱歉,我的回答有误。在第二个正则表达式中使用 '\S+' 而不是 '\S' 来捕获 1 个或多个非空白字符(例如 '+bb')而不是仅 1 个(例如 '+')。
  • 太棒了。非常感谢您的大力帮助。最后一点如何删除输出中的符号和多余的空格。
  • 我建议您阅读正则表达式以及如何使用内置的 re 模块。正则表达式是一种非常宝贵的编码技能,值得花时间熟悉它们。例如。正则表达式模式 '\w+' 将匹配一个或多个“单词字符”(字母、数字和下划线);正则表达式 "\s*" 将匹配零个或多个“空白字符”(空格、制表符等)。
猜你喜欢
  • 1970-01-01
  • 2021-02-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-08
  • 2018-11-25
  • 1970-01-01
相关资源
最近更新 更多