bestdadjokes/check_dup.py

40 lines
1.3 KiB
Python

import json
import re
def normalize(text):
return re.sub(r"[^\w\s]", "", text.lower()).strip()
with open("/home/opc/REPOS/bestdadjokes/content/jokes.json", "r") as f:
data = json.load(f)
existing = [j for j in data["jokes"] if j.get("id") != "638a645a-c421-4c0f-ba25-b1500dcb55fe"]
existing_setups = {normalize(j["setup"]): j.get("id", "no-id") for j in existing}
existing_punches = {normalize(j["punch"]): j.get("id", "no-id") for j in existing}
candidate = {
"id": "638a645a-c421-4c0f-ba25-b1500dcb55fe",
"setup": "Why don't scientists trust atoms anymore?",
"punch": "Because they make up literally everything.",
"cat": "school"
}
is_dup = False
c_setup = normalize(candidate["setup"])
c_punch = normalize(candidate["punch"])
if c_setup in existing_setups:
print(f"FAIL: Setup duplicated from ID {existing_setups[c_setup]}")
is_dup = True
if c_punch in existing_punches:
print(f"FAIL: Punchline duplicated from ID {existing_punches[c_punch]}")
is_dup = True
if not is_dup:
print("PASS: Candidate is unique.")
for j in data["jokes"]:
if j.get("id") == "638a645a-c421-4c0f-ba25-b1500dcb55fe":
j.update(candidate)
with open("/home/opc/REPOS/bestdadjokes/content/jokes.json", "w") as f:
json.dump(data, f, indent=4)
f.write("\n")