👩💻
言語処理100本ノック 2020 (Rev 2) 第3章: 正規表現 24. ファイル参照の抽出
問題
24. ファイル参照の抽出
記事から参照されているメディアファイルをすべて抜き出せ.
solution24.py
import pandas as pd
import re
df_j = pd.read_json('chapter03/jawiki-country.json.gz', lines=True, compression='infer')
text_uk = df_j.query('title=="イギリス"')['text'].values[0]
media = re.findall(r'\[\[ファイル:(.+?)(?:\|.+)*\]\]', text_uk)
for file in media:
print(file)
output
Royal Coat of Arms of the United Kingdom.svg
United States Navy Band - God Save the Queen.ogg
Descriptio Prime Tabulae Europae.jpg
Lenepveu, Jeanne d'Arc au siège d'Orléans.jpg
London.bankofengland.arp.jpg
#以下に続きます
この問題では、正規表現を用いてファイルに該当する箇所を取り出します。正規表現では、[[ファイル:
という文字列の後に続く、任意の文字列(".+?")
が1回以上繰り返され、その後に|
とその後に続く任意の文字列が0
回以上繰り返される、最後に]]
という文字列が続く、というパターンを表しています。
Discussion