题目1

import json
import pymysql
def connect_to_database():
return pymysql.connect(
host="43.143.30.32",
port=3306,
user="yingdao",
password="9527",
database="ydtest"
)
def insert_data_to_database(data, table_name):
conn = connect_to_database()
cursor = conn.cursor()
# 构建插入语句
columns = ', '.join(data.keys())
values = ', '.join(['%s'] * len(data))
sql = f"INSERT INTO {table_name} ({columns}) VALUES ({values})"
try:
cursor.execute(sql, tuple(data.values()))
conn.commit()
except Exception as e:
print(f"插入数据时出错: {e}")
conn.rollback()
finally:
cursor.close()
conn.close()
def calculate_and_insert_country_box_office(json_data):
country_box_office = {}
for movie in json_data:
country = movie["制片地区"]
box_office = float(movie["票房"])
if country in country_box_office:
country_box_office[country] += box_office
else:
country_box_office[country] = box_office
# 按照票房总数降序排序
sorted_countries = sorted(country_box_office.items(), key=lambda x: x[1], reverse=True)
# 取前三个国家
top_3_countries = sorted_countries[:3]
for i, (country, box_office) in enumerate(top_3_countries):
data = {
"提交人": '茹文博',
"信息": country,
"票房总数": box_office
}
insert_data_to_database(data, "result")
def calculate_and_insert_score_box_office(json_data):
score_box_office = {
"3.0-3.5": 0,
"9.0-9.5": 0,
"无评分": 0
}
for movie in json_data:
score = movie["评分"]
box_office = float(movie["票房"])
if score == "-":
score_box_office["无评分"] += box_office
elif 3.0 <= float(score) < 3.5:
score_box_office["3.0-3.5"] += box_office
elif 9.0 <= float(score) < 9.5:
score_box_office["9.0-9.5"] += box_office
for score_range, box_office in score_box_office.items():
data = {
"提交人": '茹文博',
"信息": score_range,
"票房总数": box_office
}
insert_data_to_database(data, "result")
def run(json_data_str):
json_data = json.loads(json_data_str)['data']
calculate_and_insert_country_box_office(json_data)
calculate_and_insert_score_box_office(json_data)
def main(args):
pass