top of page

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 = ' &emsp; &emsp; &emsp; &emsp; '


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> &emsp; {1}</quote><br>
<quote> &emsp; {2}</quote><br>
<br>
''',
    
    2: '''<hr>
<a id="{0}"></a><br>
<h2>{0}</h2>
<quote> &emsp; {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> &emsp; {1}</quote><br>
<quote> &emsp; {2}</quote><br>
<br>
''',
    
    2: '''<hr>
<a id="{0}"></a><br>
<h3>{0}</h3>
<quote> &emsp; {1}</quote><br>
<br>
''',
            
    1: '''<hr>
<a id="{}"></a><br>
<h3>{}</h3>
<br>
'''}
        """#### for parse #subsec only"""
        
        self.emsps = ' &emsp;'
        """### for parse #endsec only
        #### ' &emsp;' (3 space)"""
        
        self.nbsp = '&nbsp;'
        self.emsp = '&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>&emsp;{}</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])

最新文章

查看全部
Real Life 2405-06

Halo 聽說瘋起來連自己都反??? 制止暴力犯罪的方法很多, 從社會教育作起。 強化懲罰制度。 精心設計矯正。 連坐家族。 連坐組織。 或者, 針對犯罪者個人的嚴刑峻法: 只要犯的次數夠多,就往往會趨近於: 1. 犯罪 1 次關20天。 2. 能假釋就犯罪 1...

 
 
Real Life 202404-06, 08

sense 釋字 585 https://drive.google.com/file/d/1qWlzhVcoijIPvoQ0aJL3g1rjx_ZW7Cym/view?usp=drive_link

 
 
Real Life - Stench of The Politics of This Country

Rage of People 第二八三、 第二個問題就是能夠解釋幾乎所有我們所遭遇到的問題。 請問, 我們在多少年前, 就有能力控制那數量龐大又流轉不休的空中陣地軍? 這個問題的答案很驚人。 第二八四、 至少二十年! ...

 
 

留言


這篇文章不開放留言。請連絡網站負責人了解更多。

©2023 Ugly Deeds 版權所有。透過 Wix.com 製作的理想網站

bottom of page