ボックス について

性別:男性 考えていること、思っていることを文章にしていきます。

テキストファイルの最後に、青空文庫で使われている「#改ページ」をいれるスクリプト

すごい、ニッチなやつ。

Kindleでweb小説、たとえば東方創想話などを読みたいときwebからダウンロードして、テキストで保存する。

そしてファイルの中身を連結するソフトを使って、一つのテキストファイルにする。

このとき「#改ページ」が入っているとKindle側で章として扱ってくれる。

一つのテキストファイルにまとめないとファイル数が多くなって管理が面倒になる。

そのため、「#改ページ」を自動で入力してくれるスクリプトを書いた。

自分以外に需要がなさそう・・・

改善後

#!/usr/bin/env python
# coding: UTF-8
import os
import os.path


def main():
    list1 = os.listdir()
    list1.sort(key=os.path.getctime, reverse=False)
    print(list1)

    with open('new1.txt', 'w', encoding='utf-8') as f1:

        for filename in list1:
            if filename.endswith('.txt'):
                with open(filename, 'a+', encoding='utf-8') as f:
                   f.write('\n[#改ページ]\n')

                with open(filename, 'r', encoding='utf-8') as f:
                   a = f.read()
                   f1.write(a)

    print('Done')
    A = input('Please Any key')


if __name__ == '__main__':
    main()

 

改善前

import os
import os.path
import sys
import codecs
import pprint

list = os.listdir()
pprint.pprint(list)
list.sort(key=os.path.getctime, reverse=False)
pprint.pprint(list)
file = open("new.txt", 'a', encoding='utf-8')

for i in range(len(list)):
    if list[i] != 'text_conect.py':
        f = open(list[i], 'a', encoding='utf-8')
 
        f.write(u'[#改ページ]\n')
        f.close()

        f = open(list[i], 'r', encoding='utf-8')
        str = f.read()
        file.write(str) 
        f.close()        

file.close()

・直せそうなところ

open(), close() をwith構文を使って書き直す。

for 文のところで in range -> in list にしてわかりやすくする?

 

 

 

ストレスのはけ口

気づかないうちにストレスと抱いていることがあるかもしれない。

それをどうやって解消しているか?

自分の場合は、何かを食べるだ。

お菓子、カップ麺、うどん、弁当。

必要以上にものを食べている。それが仕方ないと自分で言い聞かせて。

逃げているのだろう。やらなくてはならないことから。

締め切りぎりぎりでやることが快楽になっているのかもしれない。

逃げていれば楽だから。目の前のことに言い訳を作ることができるから。

 

0.1%でいいから始めよう。

Python mapit.py with the webbrowser Module

# !/user/bin/env python
# -Launches a map in the browser using an address from the
# command line or clipboard

import webbrowser, sys, pyperclip


def main():
    if len(sys.argv) > 1:
        # Get address from command line
        address = ' '.join(sys.argv[1:])
    else:
        # Get address from clipboard
        address = pyperclip.paste()

    # open website
    webbrowser.open('https://www.google.com/maps/place/' + address)


if __name__ == '__main__':
    main()

コマンドラインに住所を打ち込むか、住所をクリップボードにコピーした状態でスクリプトを実行すると、グーグルマップのサイトがWebブラウザで起動して住所の場所を表示する。

サウスパーク s07e12 All About Mormons

この話で好きなセリフ

ユタから来た転校生、ゲリーの最後のセリフ

Listen, I just wanted to let you know you don’t have worry about me trying to be your friend anymore.

カイル 「I don’t?」

Look, maybe us MORMONS do believe in crazy stories that make absolutely no sense.

And maybe Joseph Smith did make it all up but I have a great life and a great family.

And I have the book of MORMON to thank for that.

The truth is, I don’t care if Joseph Smith made it all up…

Because what the church teaches now  is loving your family, being nice and helping people.

And even though people in this town might think that’s stupid, I still choose to believe in it.

All I ever did was try to be your friend, Stan.

But you’re so high and mighty you couldn’t look past my religion and just be my friend back.

You’ve got a lot of growing up to do, Buddy.

Suck my balls.(タマ、なめやがれ!)

 

最後のセリフが痛快。

論理を重視してゲリーの本当の気持ちを考えず、変な宗教であり間違ってると言い切ったカイル。

たとえモルモン教が本当でなくても、その教えによって幸せな家族と人生があるというゲリー。

 

どちらが正しいというわけではなく、何を選んで、どんな風になりたいか。

大事なことを教えてくれるエピソードだと思う。

 

I don’t care if   #しても構わない

suck #舐める

 

 

 

All About Mormons

http://southpark.cc.com/full-episodes/s07e12-all-about-mormons

Python Backing Up a Folder into a ZIP File

指定したディレクトリをバックアップするスクリプト

# !/user/bin/env python
# - Copeies an entire folder and its contents into
# a Zip file whose filename increments.

import zipfile, os


def backupToZip(folder):
    # Backup the entire contents of ''folder' into a Zip file
    folder = os.path.abspath(folder) # make sure folder is absolute
    # Figure out the filename this code should use based on what files already exist
    number = 1
    while True:
        zipFilename = os.path.basename(folder) + '_' +str(number) + '.zip'
        if not os.path.exists(zipFilename):
            break
        number += 1
    # Create Zip file.
    print('Creating {}'.format(zipFilename))
    backupzip = zipfile.ZipFile(zipFilename, 'w')

    # Walk the enter folder tree and compress the files in each folder.
    for foldername, subfolders, filenames in os.walk(folder):
        print('adding files in {}'.format(foldername))
        # Add the current folder to the Zip file.
        backupzip.write(foldername)
        # Add all the files in this folder to the zip file
        for filename in filenames:
            newBase = os.path.basename(folder) + '_'
            if filename.startswith(newBase) and filename.endswith('.zip'):
                continue
            backupzip.write(os.path.join(foldername, filename))
    backupzip.close()
    print('done')


def main():
    backupToZip("1702")



if __name__ == '__main__':
    main()

 

Python Renaming Files with American-Style Dates to European-Style Dates

アメリカ式の日付表記をヨーロッパ式の日付表記に変えるスクリプト

# !/user/bin/env python
# - Renames filenames with American MM-DD-YYYY date format
# to European DD-MM-YYYY

import shutil, os, re


def main():
    # Create a regex that matches files with American MM-DD-YYYY date format
    datePattern = re.compile(r"""
                    ^(.*?)          # all text before the date
                    ((0|1)?\d)-     # one or two digits for the month
                    ((0|1|2|3)?\d)- # one or two digits for the day
                    ((19|20)\d\d)   # four digits for the year
                    (.*?)$          # all text after the date
                    """, re.VERBOSE)

    # loop over the files in the working directory
    for amerFilename in os.listdir('.'):
        mo = datePattern.search(amerFilename)

        # Skip file without date
        if mo == None:
            continue

        # Get different parts of the file name
        beforePart = mo.group(1)
        monthPart = mo.group(2)
        daypart = mo.group(4)
        yearPart = mo.group(6)
        afterPart = mo.group(8)

        #Form the European-style filename
        euroFilename = beforePart + daypart + '-' + monthPart + '-' + yearPart + afterPart

        #Get the full, absolute file path
        absWorkingDir = os.path.abspath(".")
        amerFilename = os.path.join(absWorkingDir, amerFilename)
        euroFilename = os.path.join(absWorkingDir, euroFilename)

        # Rename the files
        print('Renameing {} to {}'.format(amerFilename, euroFilename))
        shutil.move(amerFilename, euroFilename)





if __name__ == '__main__':
    main()

 

Python import os

import os のメモ

 

# !/user/bin/env python

import os


def main():
    a = os.path.join('use', 'spam', 'bin') # パスをつなげる
    print(a) # use\spam\bin

    b = os.getcwd() # カレントディレクトリを表示
    print(b)

    c = os.chdir('C:usr') # カレントディレクトリの変更

    d = os.listdir(b) # 参照したディレクトリの中身を表示
    print(d)


if __name__ == '__main__':
    main()

 

 

Python Multiclipboard

クリップボードの値をキーワードを設定して保存するスクリプト

 

# !/user/bin/env python
# mcb.pyw - save and loads pieces of text to the clipboard
# Usage: py.exe mcb.pyw save <keyword> - Save clipboard to keyword
#        py.exe mcb.pyw <keyword> - Loads keyword to clipboard
#        py.exe mcb.pyw list - Load all keyword to clipboard

import shelve, pyperclip, sys

def main():
    with shelve.open('mcb') as mcbShelf:

        # Save clipboard content
        if len(sys.argv) == 3 and sys.argv[1].lower() == 'save':
            mcbShelf[sys.argv[2]] = pyperclip.paste()
        elif len(sys.argv) == 2:

            #List keywords and load content
            if sys.argv[1].lower() == 'list':
                pyperclip.copy(str(list(mcbShelf.keys())))
                print(str(list(mcbShelf.keys())))
            elif sys.argv[1] in mcbShelf:

                pyperclip.copy(mcbShelf[sys.argv[1]])

if __name__ == '__main__':
    main()