top of page

easyWebBook-3

holydamn20beta

請打開你的文字編輯器,複製以下內容,在你的文字編輯器裡貼上,並存成 .py 檔即可。


很傷眼,但是沒辦法。



#!/usr/python3
# encoding:utf8
# TODO: select, zenity, sys
# TODO: file name changer
# TODO: link
# TODO: comment
# TODO  subsec
# TODO  pre, code
# TODO  nbsp, emsp
from copy import deepcopy
from operator import attrgetter
import os
import sys


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'

head = '''<h1>{tex}</h1>
{log}<br>
<br>
<a href="Home.html#{date}">回到首頁</a><br>
<a id="index"></a>
<br>
'''

dict_section = {
    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>
'''}

h2 = '<h2>{}</h2>'
anch = '<a id="{}"></a>'
link = '<a href="{}#{}">{}</a>'

emsps = ' &emsp; &emsp; &emsp; &emsp; '


def create(p):
    """### Create dir if not exists"""
    os.makedirs(p, exist_ok=True)


def chdir(p):
    """### Change Current Working Folder"""
    os.chdir(p)


def filelist(p):
    """### 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, mode='r'):
    """## read file
    ### default mode is 'r'"""
    with open(f, mode) as io:
        return io.read()
    

def save(f, d, mode='w'):
    """## save file

    ### default mode is 'w'"""
    with open(f, mode) as io:
        io.write(d)


def splits_last(tex, s, n):
    """### Split Specific Steps From End"""
    return  tex.rsplit(s, maxsplit=n)


def intersects(base, middle):
    """### Intersec Lists Into 1 String"""
    if len(base) >= len(middle):
        middle.append('')
    return ''.join([''.join(_) for _ in zip(base, middle)])


def split_first(tex, s):
    """### Split and axsplit=1"""
    return  tex.split(s, maxsplit=1)


def concat(*strs) -> str:
    """### Concatenate Strings"""
    return ''.join(strs)


def group_by_amount(lst, amount):
    """### group items by amount"""
    return list(zip(*[lst[_::amount] for _ in range(amount)]))


class Path:
    def __init__(self):
        self.fs     = []
        self.months = []
        self.py     = __file__.rsplit('/', maxsplit=1)[0]
        
        # self.source = os.popen('zenity --file-selection --directory').read().strip()
        self.source = sys.argv[1]
        
        self.html   = self.source.replace('/Books/_source', '/Books/html')
        img = join_path(self.html, 'img')
        css = join_path(splits_last(self.source, '/', 2)[0],
                             '_share/styles.css')
        create(img)
        shell(f'cp {css} {img}/')
        
        self.book   = self.locate_file_by_end('.book')[0]

    def chdir(self, fd):
        fd = getattr(self, fd)
        chdir(fd)
    
    def locate_file_by_end(self, end):
        return [join_path(self.source, _)
                for _ in filelist(self.source)
                if _.endswith(end)]

    def locate_file_by_start(self, start):
        return [join_path(self.source, _)
                for _ in filelist(self.source)
                if _.startswith(start)]

    def locate_file_by_both(self, start, end):
        return [join_path(self.source, _)
                for _ in filelist(self.source)
                if _.startswith(start) and _.endswith(end)]


paths = Path()


class File:
    def __init__(self, f,):
        self.src = join_path(paths.source, f)
        f = f[:-4]
        self.dst = concat(paths.html, '/', f, '.html')
        self.name, self.month, self.id = f.split('_')
        self.mon = self.month[-2:]
        

class MChapter:
    def __init__(self, fs, m, c):
        self.name  = c
        self.month = m
        
        self.fs = [_ for _ in fs if _.name == c and _.month == m]
        self.fs.sort(key=attrgetter('id'), reverse=True)
        # self.fs = group_by_amount(self.fs, 7)
        
        if not self.fs:
            del self
        

class Month:
    def __init__(self, chap, m):
        self.fs       = []
        self.month    = m
        self.chapters = [_ for _ in chap if _.month == m]
    
    def flatten_to_fs(self):
        self.fs = [_.fs for _ in self.chapters]
        return list(sum(self.fs, []))


class Book:
    def __init__(self):
        self.ct        = []
        self._chapters = []
        self._topics   = {}
        self.book      = ''
        self.read_book_file()
        self.prepare_files()
        self.anchor = '<a id="{}"></a>'
        self.index  = '<a href="#{id}">{tex}</a>'

    def read_book_file(self):
        for _ in read(paths.book).splitlines():
            if _.startswith(' '):
                self._chapters.append(_.strip().replace(' ', ''))
            else:
                self.book = _.strip(' ')
    
    def prepare_files(self):
        fs      = [File(_) for _ in filelist(paths.source) if _.endswith('.txt')]
        months  = sorted(list(set([_.month for _ in fs])), reverse=True)
        chapt   = [MChapter(fs, m, c) for c in self._chapters for m in months]
        chapt   = [_ for _ in chapt if _.fs]
        self.ct = [Month(chapt, m) for m in months]
        
    def flatten(self):
        self.ct = [_.flatten_to_fs() for _ in self.ct]
        self.ct = list(sum(self.ct, []))
        
    def reg_topics(self, k, v, f):
        url     = ''
        if f.dst.startswith('/'):
            url = link.format(concat('file://', f.dst), k, v)
        else:
            url = link.format(concat('file:///', f.dst), k, v)
    
        if k not in self._topics:
            self._topics[k] = [url]
        else:
            self._topics[k].append(url)
        

book = Book()


def make_home_file():
    html = f'<h1>{book.book}</h1>\n{newline}'
    
    for m in book.ct:
        html += f'<h2 style="color:white;" id="{m.month}">20{m.month}</h2>\n'
        for c in m.chapters:
            html += f'<h3>{c.name}</h3>\n'
            if len(c.fs) >= 7:
                group_by_amount(c.fs, 7)
                for g in c.fs:
                    for f in g:  
                        html += f'<a href="{f.dst}">{f.id}</a> &emsp;&emsp;&emsp;'
                    html += newline
                html += newline
            else:
                for f in c.fs:
                    html += f'<a href="{f.dst}">{f.id}</a> &emsp;&emsp;&emsp;'
                html += newline
        html += newline
    
    html += '''<h2 style="color:white" id="and">And</h2>
<h3><a href="topics.html">Topics</a></h3>
<br>
'''
    html = frame.format(body=html)
        
    save(join_path(paths.html, 'Home.html'),
              html)


PosReplacing = (
    ('***', '<b><i>', '</i></b>'),
    ('**', '<b>', '</b>'),
    ('*', '<i>', '</i>'),
    ('~~', '<s>', '</s>')
)


def pos_replacing(r, tag, head, tail):
    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)


def replace_anchor(line, f):
    k, v = line.strip().split('|')[-2:]
    book.reg_topics(k, v, f)
    return book.anchor.format(v)


def make_page_file():
    for f in book.ct:
        index = []
        raw = read(f.src).strip()
        
        for symbols in PosReplacing:
            raw = pos_replacing(raw, *symbols)
                
        chapter, raw = split_first(raw, '\n')
        chapter = chapter.split('|')[-3:]
        chapter_tex = intersects(chapter, ['_', ' &emsp; '])
        
        # region [ rgba(255, 0, 255, 0.1) ] ━━━━━━━━━━━━ PAGE HEAD
        
        if raw.startswith('#log'):
            log, raw = split_first(raw, '#endlog')
            log = newline.join(log.splitlines()[1:])
            header = head.format(tex=chapter_tex, log=log, date=chapter[1])
        else:
            header = head.format(tex=chapter_tex, log='', date=chapter[1])    
        
        # endregion ─────────────────────────────
        
        raw = splits_last(raw.strip(), '#endchapter', 1)[0].strip()
        html = ''

        # region [ rgba(0, 255, 255, 0.03) ] ━━━━━━━━━━━━ Sections
        
        secs = raw.split('#sec|')[1:]
        
        for sec in secs:
            sec = sec.splitlines()
            section = sec[0].split('|')
            index.append(link.format('', section[0], section[0]))
            
            sec[0] = dict_section[len(section)].format(*section)
            
            for i, _ in enumerate(sec[1:]):
                if _.startswith('#anchor|'):
                    sec[i + 1] = replace_anchor(_, f)    
                
                elif _.strip() == '#endsec':
                    sec[i + 1] = '''<br>
{space} <a href="Home.html#{date}">回到首頁</a>{divid}<a href="#index">回到頂端</a><br>
'''.format(space=' &emsp;' * 21, date=chapter[1], divid = ' &emsp;' * 3)
            
            html += '<br>'.join(sec)
        
        # endregion ─────────────────────────────
        
        # region [ rgba(255, 255, 0, 0.06) ] ━━━━━━━━━━━━━ Index
        
        if len(index) > 7:
            index = group_by_amount(index, 8)
            index = str(newline + newline).join([emsps.join(_) for _ in index])
        else:
            index = emsps.join(index)
        
        index += newline
        
        # endregion ─────────────────────────────
        html = frame.format(body=header + index + html)
        save(f.dst, html)


def make_topic():
    keys = sorted(list(book._topics.keys()))
    html = ''
    
    for k in keys:
        html += f'<h2 id="{k}">{k}</h2>\n'
        v = sorted(book._topics[k])
        # v = [[_, calc_length(_)] for _ in v]
        
        if len(v) == 1:
            html += v[0] + newline
            continue
        
        tex = [_.split('>')[1].split('<')[0] for _ in v]
        ref = [''.join(['1' for _ in x]) for x in tex]
        ref = str('0' * len(emsps)).join(ref)
        
        while ref:
            r = ref[:84]
            
            if r.endswith('1'):
                r = list(filter(None, r.split('0')[:-1]))
            else:
                r = list(filter(None, r.split('0')))
            
            tex = v[:len(r)]             
            html += emsps.join(tex) + newline

            ref = ref[84:]
        
        html += newline

    html = frame.format(body=html)
    save(join_path(paths.html, 'topics.html'),
              html)


if __name__ == "__main__":
    make_home_file()
    book.flatten()
    make_page_file()
    make_topic()

0 次查看0 則留言

最新文章

查看全部

easyWebBook-4

alpha 1,easyWebbBok.py,

Comentarios


Los comentarios se han desactivado.

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

bottom of page