Pythonでやってみよ。ファイル操作、つづき
毎日、自分で投稿したnoteの記事一覧を取得して、ダッシュボードのコメント数推移をみる表を作っています。昨日pythonでファイル操作をやってみたわけですが、せっかくですので、つづきです。
記事用のディレクトリに、記事ごとにテキストファイルに保存してます。こうしておくと、そのディレクトリの中のファイル数で投稿した数がわかりますし、内容も表示することも、同じような内容を書いているかもわかるようになって便利です。
まず復習。
#記事ごとにテキストファイルとして保存。
>>> z_=get_note_articlelist(dy_='202507280000',tt_=10)
$ pn -c "$imt;z_=get_note_articlelist(dy_='202507280000',tt_=10)"
#では、記事が保存されているディレクトリからファイルを取得
>>> lt_=[x for x in pathlib.Path.cwd().glob('**/*.txt')]
#ファイル数を表示
>>> len(lt_)
49
#49個の記事ファイルから「note_article」あるいは「note_dashboard」を含むファイルを取得して、ファイル名を表示。2つありました。
>>> pr_joinn([x.name for x in lt_ if re_.search(x.read_text())])
notecom_codingkiwi_Pythonでやってみよ。記事一覧の取得のつづき_202507311504.txt
notecom_codingkiwi_Pythonでやってみよ。noteダッシューボードのコメント数推移_202507301604.txt
#ファイル名と前3行後2行を表示してみましょう
>>> exec("an_=[];ans_=''\nfor x in [x for x in lt_ if re_.search(x.read_text())]:\n for i in [i for i,x in enumerate(x.read_text().split(chr(10)),1) if re_.search(x)]:\n for ii in range(i-3,i+2+1):\n an_+=[[str(i)+':'+y for i,y in enumerate(x.read_text().split(chr(10)),1)][ii]]\n an_=sorted(set(an_))\n ans_+=x.name+'\\n'+'\\n'.join(sorted(an_))+'\\n-----\\n\\n'\n an_=[]\n\npr(ans_[:-8])\n")
#結果です。
notecom_codingkiwi_Pythonでやってみよ。記事一覧の取得のつづき_202507311504.txt
25:#使い方vv
26:#pythonでBeautifulSoupでnoteの記事一覧取得する方法vv
27:>>> z_=get_note_articlelist(dy_='202507280000',tt_=10)
28:$ pn -c "$imt;z_=get_note_articlelist(dy_='202507280000',tt_=10)"
29:#--- 2025-07-07 13:58:50 +0900 ---
30:追加(htmlのソースをコピーするのではなく、seleniumで取得する版)
31:#--- 2025-07-30 22:55:19 +0900 ---
35:こちらが、自作関数です。
36:
37:def get_note_articlelist(url='https://note.com/coding_kiwi',dwd='~/Downloads/note_codingkiwi2/',f_='notecom_codingkiwi',dy_='202505200000',tt_=10):
38:'''
39:seleniumでwebから記事を取得して保存(firefox版)
40:'''
notecom_codingkiwi_Pythonでやってみよ。noteダッシューボードのコメント数推移_202507301604.txt
60:--- 2025-07-24 18:07:35 +0900 ---
61:
62:ダッシュボードのページを開いてhtmlのテーブル部分のソースをコピペするのもなんだかなぁ、と思ってしまい、とうとう「selenium」を使って、自動化をやってみました。「get_note_dashboard」がその自作関数です。
63:そして、複数ファイル名をコピーして、というのもなんだかなぁ、なので、こちらも「pathlib」を使って比較するファイルを取得するようにしてみました。
64:
65:#使い方vv
66:#pythonでnoteのダッシュボードのテーブルのhtmlをコピーしてpolarsで表形式でvimで表示する方法vv
67:#pythonでpandasでnoteのダッシュボードのテーブル値を取得してpolarsで加工して表テキストにしてvimで表示、表テキストとparquet形式で日付を付けて保存する方法vv
68:$ pn -c "$imt;ans_=get_note_dashboard('https://note.com/sitesettings/stats')" #note_dashboard_by_selenium__
69:$ pn -c "$imt;lt_=sorted([x.name for x in pathlib.Path('~/').expanduser().glob('**/*.txt') if re.search('^note_dashboard_\d*?.txt',x.name) and datetime.datetime.strptime(x.name[:-4].split('')[-1],'%Y%m%d%H%M%S').astimezone()>datetime.datetime(2025,7,22).astimezone()],key=lambda x:pathlib.Path(x).name[:-4].split('')[-1]);s1_='[│┌└┬┴┐╞╪├┼┤╌─═┘╡]';s2_='┆';exec(\"for i,f in enumerate(lt_):\\n fm_='~/pn/'+f;rr_=locals()[f'r{i}']=''+datetime.datetime.strptime(fm[:-4].split('')[-1],'%Y%m%d%H%M%S').strftime('%Y-%m-%d%H%M%S')\\n a_=[[x.strip(' ') for x in x.split(s2_)] for x in [x for x in re.sub(s1_,'',pathlib.Path(fm_).expanduser().read_text()).split('\\\\n') if x!='']]\\n col_=[x+rr_ if not x=='記事' else x for x in a_[1]];a1_=a_[4:]\\n b_=a1_[:-1];c_=a1_[-1]\\n locals()[f'df_{i}']=pl.DataFrame(b_,schema=col_,orient='row').with_columns(pl.col('^(ビュー|コメント|スキ)$').str.replace(',','').cast(pl.Int64))\\n locals()[f'df0_{i}']=pl.DataFrame([c_],schema=col_,orient='row').with_columns(pl.col('^(ビュー|コメント|ス
70:キ)$').str.replace(',','').cast(pl.Int64))\");e_='';exec(\"for i,f in zip(range(len(lt_))[::-1],lt_[::-1]):\\n if i+1==len(lt_):\\n e_='df_z=df_'+str(i)\\n elif 0<=i+1<len(lt_):\\n e_+='.join(df_'+str(i)+',on=\\\\'記事\\\\',how=\\\\'full\\\\',suffix=\\\\''+str(i)+'\\\\')'\\n else:pass\");exec(e_);df_z=df_z.select(pl.exclude('^記事.+?$')).with_columns(pl.col('^[ビコス].*?$').cast(pl.Int64));df_ans_=df_z.select([pl.col('記事'),pl.col('^ビュー.*?$'),pl.col('^スキ.*?$'),pl.col('^コメント.*?$'),pl.col('^日付.*?$')]);df_ans_=pl.concat([df_ans_,pl.DataFrame([('合計',)+x[1:] for x in df_ans_.sum().iter_rows()],schema=df_ans_.columns,orient='row')]);z_=df_ans_.write_excel('note_dashboard_'+fm_[:-4].split('')[-1]+'.xlsx');z=df_ans_.write_parquet('note_dashboard_'+fm_[:-4].split('')[-1]+'.parquet');z=pl.Config.load(plcfg);to_vim(str(df_ans_));to_vim(tabulate([('\n'.join(textwrap.wrap(x[0],width=15)),)+x[1:] for x in df_ans_.iter_rows()],headers=[re.sub('','\n',x,2) for x in df_ans.columns],tablefmt='fancy_grid',intfmt=
71:','))" #note_dashboard_vs__
面倒ではありますが、記事を書くときに以前の記事にあるかどうか、どう書いていたかが確認できるのはとてもいいですよね。とはいえひとつひとつファイルを開いて確認したり、わざわざWebを開いて確認するよりは、格段に効率的でなによりも時短です。
