前提
Python及びプログラム初心者です。自分なりに調べても解決法が分からず質問させていただきました。よろしくお願い致します。
https://serenard.hatenablog.com/entry/2019/04/07/164337
このサイトを参考に青空文庫のgitのレポジトリをクローンしたものから文書をダウンロードし、その文書をクレンジングしたものを改めて別ファイルに保存という作業を行っていたのですが、最後の保存の途中でエラーが起きました。
実現したいこと
- ▲▲エラーを直し保存したい
発生している問題・エラーメッセージ
D:\aozorabunko>python henkan.py saved ./novels/岡本かの子/愚なる(?!)母の散文詩 Traceback (most recent call last): File "D:\aozorabunko\henkan.py", line 42, in <module> save_novel('./novels/' + novel_author.string + '/' + novel_title.string, novel_content.text) File "D:\aozorabunko\henkan.py", line 13, in save_novel with open(file_path, 'w') as f: OSError: [Errno 22] Invalid argument: './novels/岡本かの子/愚なる(?!)母の散文詩'
該当のソースコード
Python
1from bs4 import BeautifulSoup as bs 2import numpy as np 3 4import re, sys, os 5 6def make_dir(dir_name): 7 if not os.path.exists(dir_name): 8 os.mkdir(dir_name) 9 10def save_novel(file_path, text): 11 if not os.path.exists(file_path): 12 print('saved', file_path) 13 with open(file_path, 'w') as f: 14 f.write(text) 15 16if __name__ == '__main__': 17 pass 18 19 cards = os.listdir('./cards') 20 21 for card in cards: 22 if card.isdecimal() and os.path.exists('./cards/' + card + '/files'): 23 novels = os.listdir('./cards/' + card + '/files') 24 for novel in novels: 25 26 if novel[-4:] == 'html': 27 with open('./cards/' + card + '/files/' + novel, 'r') as f: 28 novel_page_html = f.read() 29 novel_parsed = bs(novel_page_html, 'html.parser') 30 try: 31 for rt in novel_parsed('rt'): 32 rt.decompose() 33 for rp in novel_parsed('rp'): 34 rp.decompose() 35 except AttributeError as err: 36 print(err) 37 novel_title = novel_parsed.find('h1', class_='title') 38 novel_author = novel_parsed.find('h2', class_='author') 39 novel_content = novel_parsed.find('div', class_='main_text') 40 if novel_author is not None and novel_author.string is not None: 41 make_dir('./novels/' + novel_author.string) 42 save_novel('./novels/' + novel_author.string + '/' + novel_title.string, novel_content.text)
試したこと
保存する作品のタイトルの?や!の文字が問題なのかと思いましたが調べてもいまいちコードのどの部分に手を加えてよいのか分からず何もできておりません。
補足情報(FW/ツールのバージョンなど)
Python3.9
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2022/09/14 10:32
2022/09/14 10:45
2022/09/14 11:15