0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

たまりにたまったタブの整理のためにMarkdownのリンクをソートする

Posted at

たまりにたまったタブの整理のためにMarkdownのリンクをソートする

モチベーション

ブラウザのタブが 100 個とかになっていることがよくあると思うのですが、そうなるといちいち見返す気にならない。

なのでとりあえずタブのタイトルをマークダウン形式で抽出して、それを眺めるということをしています。

ただし適当に開いておいただけのタブですからタブの重複、時系列の逆転などがあり見にくいのでソートしてしまえ!という記事です。

バージョンはセイウチ演算子を使うので Python 3.8 以降です。

コード

markdown_parse.py
""" マークダウンリンクをソートするプログラム """
import re


def paste2list(text: str | None) -> list[list[str]]:
    """マークダウンのリンクをパースして[title, url] にして返す"""

    # ここで text が None でないことを保証
    assert text != "", "text must not be empty"
    assert text is not None, "text must not be None"
    # あるいは
    # if text is None:
    #     return []
    # この場合はどちらかといえば引数のミスを教えてほしいかな?

    # 正規表現をコンパイルしておく
    link_pattern = re.compile(r"\[(.*?)\]\((.*?)\)")

    lines = [
        link
        for line in text.split("\n")
        if (link := line.strip())  # 空行あるいはスペースだけの行をスキップ
        # ":=" はセイウチ演算子。式の中で変数に代入し、その値を同時に評価できる
    ]

    return [
        [match.group(1), match.group(2)]
        for line in lines
        if (match := link_pattern.match(line))
        # match() はマッチしないとき None を返すのでフィルターとして働く
    ]


if __name__ == "__main__":

    PASTE = """[Xユーザーのゆどんさん: 「よもぎ大福が美味すぎる。なんだコレ。チャンスか?」 / Twitter](https://x.com/Yudon66/status/1968155697151086746)
[Xユーザーのゆどんさん: 「朝から広島お好み焼きを作って食べた! 大満足で、これから寝る!」 / Twitter](https://x.com/Yudon66/status/1926414425478574569)
[Xユーザーのゆどんさん: 「マルタイ美味すぎ警報発令中」 / Twitter](https://x.com/Yudon66/status/1945730562460946513)"""

    for i in sorted(paste2list(PASTE), key=lambda x: x[1]):
        print(i)

# ['Xユーザーのゆどんさん: 「朝から広島お好み焼きを作って食べた! 大満足で、これから寝る!」 / Twitter', 'https://x.com/Yudon66/status/1926414425478574569']
# ['Xユーザーのゆどんさん: 「マルタイ美味すぎ警報発令中」 / Twitter', 'https://x.com/Yudon66/status/1945730562460946513']
# ['Xユーザーのゆどんさん: 「よもぎ大福が美味すぎる。なんだコレ。チャンスか?」 / Twitter', 'https://x.com/Yudon66/status/1968155697151086746']

終わり

簡単なプログラムだと思って書き始めたが

  • 型パズル
  • セイウチ演算子

あたりが以外に面白かった。

また

  • ドメイン絞り込み
  • 逆順
  • 他の形式にする

みたいなこともちょっと書き直せばできる。

Link

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?