easyWebBook-5
- holydamn20beta
- 2023年12月19日
- 讀畢需時 3 分鐘
請將兩個檔案放在同一個目錄底下。
tools_and_settings.py
#!/usr/python3
# encoding:utf8
import os
# 自動改檔名
autorename=True
# 選擇txt檔目錄的方式
# filesource: str = os.popen('zenity --file-selection --directory').read().strip()
filesource: str = '' # 手動輸入固定目錄。
# filesource: str = sys.argv[1]
shell = os.system
frame = '''<!DOCTYPE html>
<html>
<meta charset="utf-8">
<head>
<link rel="stylesheet" href="img/styles.css">
</head>
<body>
{body}
</body>
</html> '''
newline = '<br>\n'
h = '<h{n}>{tex}</h{n}>\n'
link = '<a href="{url}#{sect}">{tex}</a>'
emsps = '         '
def create_dir(p: str) -> None:
"""### Create dir if not exists"""
os.makedirs(p, exist_ok=True)
def chdir(p: str) -> None:
"""### Change Current Working Folder"""
os.chdir(p)
def filelist(p: str) -> list:
"""### Get FileList of A Folder (Relative)"""
return [_ for _ in os.listdir(p) if os.path.isfile('/'.join([p, _]))]
def join_path(*path):
"""### Join Path"""
return '/'.join(path)
def read(f: str, mode='r') -> str:
"""## read file
### default mode is 'r'"""
with open(f, mode) as io:
return io.read()
def save(f: str, d, mode='w') -> None:
"""## save file
### default mode is 'w'"""
with open(f, mode) as io:
io.write(d)
def splits_last(tex: str, s: str, n: int) -> list:
"""### Split Specific Steps From End"""
return tex.rsplit(s, maxsplit=n)
def split_first(tex: str, s: str) -> str:
"""### Split and axsplit=1"""
return tex.split(s, maxsplit=1)
def concat(*strs) -> str:
"""### Concatenate Strings"""
return ''.join(strs)
def group_by_amount(lst: list, amount: int) -> list:
"""### group items by amount"""
return list(zip(*[lst[_::amount] for _ in range(amount)]))
PosReplacing = (
('***', '<b><i>', '</i></b>'),
('**', '<b>', '</b>'),
('*', '<i>', '</i>'),
('~~', '<s>', '</s>'),
('`', '<code>', '</code>')
)
def pos_replacing(r: str, tag: str, head: str, tail: str) -> str:
if tag not in r:
return r
n = r.split(tag)
for i, _ in enumerate(n):
if i % 2 != 0:
n[i] = ''.join([head, _, tail])
return ''.join(n)
class TagsParser:
def __init__(self):
self.chapter: str = ''
"""#### Chapter Name of This File"""
self.f: str = ''
"""#### FileName of Current File"""
self.index: list = []
"""#### List of Sections and SubSections Anchors"""
self.sec_selector = {
3: '''<hr>
<a id="{0}"></a><br>
<h2>{0}</h2>
<quote>   {1}</quote><br>
<quote>   {2}</quote><br>
<br>
''',
2: '''<hr>
<a id="{0}"></a><br>
<h2>{0}</h2>
<quote>   {1}</quote><br>
<br>
''',
1: '''<hr>
<a id="{}"></a><br>
<h2>{}</h2>
<br>
'''}
"""#### for parse #sec only"""
self.subsec_selector = {
3: '''<hr>
<a id="{0}"></a><br>
<h3>{0}</h3>
<quote>   {1}</quote><br>
<quote>   {2}</quote><br>
<br>
''',
2: '''<hr>
<a id="{0}"></a><br>
<h3>{0}</h3>
<quote>   {1}</quote><br>
<br>
''',
1: '''<hr>
<a id="{}"></a><br>
<h3>{}</h3>
<br>
'''}
"""#### for parse #subsec only"""
self.emsps = '  '
"""### for parse #endsec only
#### '  ' (3 space)"""
self.nbsp = ' '
self.emsp = ' '
self.anchr = '<a id="{}"></a>'
"""#### '<a id="`{}`"></a>'"""
self.head = '''<h1>{tex}</h1>
{log}<br>
<br>
<a href="Home.html#{date}">回到首頁</a><br>
<a id="index"></a>
<br>
'''
self.quote: str = '<quote> {}</quote>'
self.current_sec: str = ''
self.opened: bool = False
"""#### status flag for multiple lines tags but sec or subsec"""
self.method = False
"""#### method holder for multiple lines tags but sec or subsec"""
self.url_file = '<a href="file:///{url}.html{suffix}"><{tex}</a>'
"""#### '<a href="file:///{url}.html{suffix}"><{tex}</a>'"""
self.url_web = '<a href="https://{url}.html{suffix}"><{tex}</a>'
"""#### '<a href="https://{url}.html{suffix}"><{tex}</a>'"""
self.url_image = '<img src="img/{}" alt="">'
"""#### '<img src="img/{}" alt="">'"""
def setup(self, chapter: str, f: str) -> None:
self.chapter = chapter
self.f = f
self.index = []
def parse_tag(self, row: str) -> str:
tags = row.strip().split('|')
method = tags.pop(0)[1:]
if method in ('q', 'cmt') and not self.opened:
self.method = getattr(self, method)
self.opened = True
return '#del|'
elif method in ('endq', 'endcmt') and self.opened:
self.method = False
self.opened = False
return '#del|'
else:
pass
return getattr(self, method)(row, *tags)
def sec(self, row: str, *tags) -> str:
self.index.append(link.format(url='', sect=tags[0], tex=tags[0]))
self.current_sec = tags[0]
return self.sec_selector[len(tags)].format(*tags)
def endsec(self, row: str, *tags) -> str:
return '''<br>
{space} <a href="Home.html#{date}">回到首頁</a>{divid}<a href="#index">回到頂端</a><br>
'''.format(space=self.emsps * 21, date=self.chapter, divid = self.emsps * 3)
def subsec(self, row: str, *tags) -> str:
name = concat(self.current_sec, '-', tags[0])
self.index.append(link.format('', tags[0], tags[0]))
return self.subsec_selector[len(tags)].format(*tags)
@staticmethod
def endsubsec(row: str, *tags) -> str:
return newline
def q(self, row: str, *tags) -> str:
return self.quote.format(row)
@staticmethod
def cmt(row: str, *tags) -> str:
return '#del|'
@staticmethod
def ins(row: str, *tags) -> str:
return '<pre>'
@staticmethod
def endins(row: str, *tags) -> str:
return '</pre>'
def anchor(self, row: str, *tags) -> str:
self.book.reg_topics(tags[-2], tags[-1], self.f)
return self.anchr.format('_'.join(tags))
def lnk(self, row: str, *tags) -> str:
return getattr(self, f'link_{tags.pop(0)}')(row, *tags)
def link_file(self, row: str, *tags) -> str:
string = ''
if len(tags) == 2:
string = self.url_file.format(url=tags[1], suffix='', tex=tags[0])
else:
string = self.url_file.format(url=tags[1], tex=tags[0],
suffix=concat('#', tags[2]))
return string.replace('////', '///')
def link_web(self, row: str, *tags) -> str:
string = ''
if len(tags) == 2:
string = self.url_web.format(url=tags[1], suffix='', tex=tags[0])
else:
string = self.url_web.format(url=tags[1], tex=tags[0],
suffix=concat('#', tags[2]))
return string.replace('////', '///')
def link_image(self, row: str, *tags) -> str:
return self.url_image.format(tags[0])
留言