From 2bf66d6037f54a263e72c23b18d739955e526530 Mon Sep 17 00:00:00 2001 From: p6fxi93qh <1240380517@qq.com> Date: Tue, 17 Sep 2024 23:34:15 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BD=BF=E7=94=A8=E5=A4=9A=E7=BA=BF=E7=A8=8B?= =?UTF-8?q?=E4=BC=98=E5=8C=96=E4=BB=BB=E5=8A=A11=E5=8A=A0=E9=80=9F?= =?UTF-8?q?=E8=8E=B7=E5=8F=96=E5=BC=B9=E5=B9=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- task1_2.py | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 task1_2.py diff --git a/task1_2.py b/task1_2.py new file mode 100644 index 0000000..9b0d8f2 --- /dev/null +++ b/task1_2.py @@ -0,0 +1,30 @@ + +from concurrent.futures import ThreadPoolExecutor +import os +import threading +from getdm import get_videos_url,get_danmu + +def write_dm_to_file(video_id, file, lock): + danmu = get_danmu(video_id) + with lock: + for item in danmu: + file.write(f"{item}\n") # 每个弹幕单独一行 + print(f"视频 {video_id} 的弹幕已写入") + +def writedmtxt(file_path, res): + with open(file_path, 'w', encoding='utf-8') as file: + lock = threading.Lock() + with ThreadPoolExecutor(max_workers=10) as executor: + futures = [executor.submit(write_dm_to_file, video_id, file, lock) for video_id in res] + for future in futures: + future.result() # 获取函数结果,这里可以用来处理异常 + +if __name__ == '__main__': + keyword = '2024巴黎奥运会' + res = get_videos_url(keyword, 10) + res_dir = os.path.join(os.getcwd(), 'res') + if not os.path.exists(res_dir): + os.makedirs(res_dir) + file_name = "total300_3.txt" + file_path = os.path.join(res_dir, file_name) + writedmtxt(file_path=file_path, res=res) \ No newline at end of file