>>> from env_helper import info; info()
页面更新时间: 2024-04-06 23:08:31
运行环境:
Linux发行版本: Debian GNU/Linux 12 (bookworm)
操作系统内核: Linux-6.1.0-18-amd64-x86_64-with-glibc2.36
Python版本: 3.11.2
1.6. 案例:使用电子表格生成章节结构¶
1.6.1. 场景说明¶
根据电子表格内容生成Jupyter章节的结构。
1.6.2. 解决思路¶
1.6.3. 解决方法¶
>>> from pprint import pprint
>>> import openpyxl
>>> wb = openpyxl.load_workbook('contents.xlsx')
>>>
>>> sheet = wb.active
>>> # print(sheet.title)
>>>
>>> cnt_arr = []
>>> the_key = None
>>>
>>> sub_arr = []
>>> the_dic = {
>>>
>>> }
>>>
>>> tmpl = open('book_tmpl.md').read()
>>> for i in range(1, sheet.max_row + 1):
>>> the_val = sheet.cell(row=i, column=1).value
>>> if the_val:
>>> pass
>>> else:
>>> continue
>>>
>>> if the_val.startswith(' '):
>>> sub_arr.append(the_val.strip())
>>> pass
>>> else:
>>> the_key = the_val
>>>
>>> the_dic['subs'] = sub_arr
>>> cnt_arr.append(the_dic)
>>>
>>> the_dic = {
>>> 'title': the_key
>>> }
>>>
>>> sub_arr = []
>>>
>>> the_dic['subs'] = sub_arr
>>> cnt_arr.append(the_dic)
>>> import os
>>> import sys
>>>
>>> outdir = 'xx_book'
>>> if os.path.exists(outdir):pass
>>> else: os.mkdir(outdir)
>>>
>>> chidx = 1
>>> for cnt in cnt_arr:
>>> the_dirit = cnt.get('title')
>>> if the_dirit:
>>> the_dirit = the_dirit.strip()
>>> the_dir = '{}/xx_ch{}0_{}'.format(outdir, str(chidx).zfill(2), the_dirit)
>>> else:
>>> continue
>>> sub_files = cnt['subs']
>>> if os.path.exists(the_dir):
>>> pass
>>> else:
>>> os.mkdir(the_dir)
>>> secindx = 1
>>>
>>> with open( os.path.join(the_dir, 'chapter.md'), 'w') as fo:
>>> fo.write(
>>> tmpl.replace('xxxx',
>>> the_dirit)
>>> )
>>>
>>> for wfile in sub_files:
>>> the_file = os.path.join(
>>> the_dir, 'sec{}_{}.md'.format(
>>> secindx, wfile
>>> )
>>> )
>>> with open(the_file, 'w') as fo:
>>> fo.write(
>>> tmpl.replace('xxxx',
>>> wfile )
>>> )
>>> secindx = secindx + 1
>>>
>>> chidx = chidx + 1