From b1d0f996b873e3df25ed2ebdd779dd2e26f045fd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=B0=A2=E5=98=89=E6=80=A1?= <2509165002@student.example.com> Date: Thu, 2 Apr 2026 16:02:46 +0800 Subject: [PATCH] =?UTF-8?q?=E4=B8=8A=E4=BC=A0=E6=96=87=E4=BB=B6=E8=87=B3?= =?UTF-8?q?=20/?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Test.py | 67 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 Test.py diff --git a/Test.py b/Test.py new file mode 100644 index 0000000..33ae709 --- /dev/null +++ b/Test.py @@ -0,0 +1,67 @@ +import requests +import re +import csv +import json + +url = "https://movie.douban.com/top250" +headers = { + "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36" +} + +response = requests.get(url, headers=headers) +html = response.text + +pattern = re.compile( + r'(\d+).*?' + r'(.*?).*?' + r'(.*?).*?' + r'(.*?).*?' + r'(\d+人评价).*?' + r'(.*?)?', + re.S +) + +movies = pattern.findall(html)[:10] + +movie_list = [] +for m in movies: + rank = m[0] + title = m[1] + en_title = m[2].replace("/", "").strip() + rating = m[3] + people = m[4] + quote = m[5] if len(m) > 5 else "" + movie_list.append({ + "rank": int(rank), + "title": title, + "en_title": en_title, + "rating": rating, + "people": people, + "quote": quote + }) + +with open("movies.txt", "w", encoding="utf-8") as f: + for m in movie_list: + f.write(m["title"] + " | " + m["quote"] + "\n") + + +with open("movies.csv", "w", encoding="utf-8-sig", newline="") as f: + writer = csv.writer(f) + + writer.writerow(["排名", "中文名", "英文名", "评分", "评价人数", "经典评语"]) + for m in movie_list: + writer.writerow([m["rank"], m["title"], m["en_title"], m["rating"], m["people"], m["quote"]]) +print("✅ 练习1完成:已保存到 movies.csv") + +with open("movies.json", "w", encoding="utf-8") as f: + json.dump(movie_list, f, ensure_ascii=False, indent=4) +print("✅ 练习2完成:已保存到 movies.json") + + +print("\n--- 练习3:JSON统计 ---") +with open("movies.json", "r", encoding="utf-8") as f: + data = json.load(f) + +ratings = [float(m["rating"]) for m in data] +avg = sum(ratings) / len(ratings) +print(f"平均分:{avg:.2f}") \ No newline at end of file