Huaiyao Jin

Huaiyao Jin

用 Python 重写 "那年今日"

这两天重新过了一遍 Python 的基础语法,今天花了一点时间把“那年今日”的 shell 脚本用 Python 实现一下,记录在此。

原先的 shell 脚本内容:

cd  "/Users/jinhuaiyao/Library/Mobile Documents/iCloud~com~logseq~logseq/Documents/journals"
DT=`date +%m_%d`;
> ../pages/On_This_Day.md;
ls |grep "_$DT" |sort |while read file
do
echo $file |sed 's/.md//g'|sed 's/_/-/g' |sed 's/^/- -------- [[/g' |sed 's/$/]] --------/g' >> ../pages/On_This_Day.md

cat "$file" >> ../pages/On_This_Day.md
echo -e "\n" >> ../pages/On_This_Day.md

echo "-" >> ../pages/On_This_Day.md
echo "-" >> ../pages/On_This_Day.md
echo "-" >> ../pages/On_This_Day.md
done

改写以后的 Python 脚本:

import time, os, fnmatch

base_dir = "/Users/jinhuaiyao/Library/Mobile Documents/iCloud~com~logseq~logseq/Documents"
journal_dir = f"{base_dir}/journals"
filename = f"{base_dir}/pages/On_This_Day2.md"

with open(filename, 'w') as file_object:
    file_object.write('')

# print(filename)

today_date_str = time.strftime("%m_%d", time.localtime())  # e.g. 02_16
# print(today_date_str)

today_date_files = []

for f_name in os.listdir(journal_dir):
    """search file to get files with this day"""
    if fnmatch.fnmatch(f_name, f'*_{today_date_str}.md'):
        today_date_files.append(f_name)

today_date_files.sort()

# print(today_date_files)

# from '2011_02_16.md' to get '- -------- [[2011-02-16]] --------'
# print('- -------- [[' + today_date_file[0].replace('.md','').replace('_','-') + ']] --------')

for today_date_file in today_date_files:
    today_file = f"{journal_dir}/{today_date_file}"
    with open(filename, 'a') as target_file, open(today_file) as source_file:
        """generate header"""
        target_file.write('- -------- [[' + today_date_file.replace('.md','').replace('_','-') + ']] --------\n')

        """copy each file"""
        for line in source_file:
            target_file.write(line)

        target_file.write('\n')
        target_file.write('-\n')
        target_file.write('-\n')
        target_file.write('-\n')

Python 脚本写得相对少很多,先实现功能,以后再优化。