You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python实现输入症状与疾病症状列表匹配并输出最优匹配

症状检测疾病项目的问题与优化

作为编程初学者,我在开发一个通过症状检测疾病的项目时遇到了问题。项目核心需求是让用户输入症状后,程序将输入与预设的疾病症状列表匹配,选出最优匹配结果输出。目前的问题是不同疾病的症状列表存在少量共同症状,因此程序需要评估所有列表以确定最优匹配。我尝试编写了如下代码:

import re

input1 = input("Enter Your Symptoms: ".lower())
x = re.split("\\s", input1)  #used to seprate the words in the string and create a list out of it

# Symptoms
cadsym = ['chest pain' , 'body pain' , 'falling sick' , 'feeling faint' , 'shortness of breath']
vhdsym = ['swollen ankles' , 'fanting' , 'shortness of breath']
hasym = ['racing heartbeat', 'slow heartbeat', 'chest pain' , 'anxiety', 'sweating']
mhasym = ['cold sweat', 'heartburn', 'sudden dizziness', 'discomfort in joints']
jsym = ['itching', 'abdominal pain', 'weight loss', 'yellow eyes' , 'yellow nails', 'vomiting']
cpsym = ['rashes on skin' , 'fever' , 'sore throat' , 'brown spots' , 'itching']
msym = ['fever', 'runny nose' , 'sneezing' , 'pink eye' , 'skin rash', 'diarrhoea']
dsym = ['Eye pain' , 'fever' , 'muscle pain' , 'nausea' , 'joint pain', 'rash on thigh']
masym = ['pain in muscle' , 'pain in abdomin' , 'Night sweat' , 'shivering', 'fast heart rate' , 'mental confusion']
tcsym = ['chest pain','Night sweats','shortness of breath','blood cough']
disym = ['increase thirst','frequent urination','hunger','blurred vision','slow healing']
pnsym = ['fever','chills','sharp pain in chest','clammy skin']
htsym = ['nose bleeds','dizziness','morning headaches','irregular heart rhythms','vision changes','buzzing in the ears']
emsym = ['lot of mucus','tight chest','whistle sound while breathing']
cysym = ['bluish colour in sikn',' lips','nail beds']
hysym = ['itchy','red and watery eyes','rod of mouth being itchy','runny or blocked nose']
ansym = ['unusual headache','memory loss','slurred speech','forgotten words','trouble in walking','trouble in moving arms','trouble in moving legs']
hcsym = ['anxiety','shortness of breath','headache','daytime sleep even after sleeping a lot at night','daytime sluggishness']
bcsym = ['sleeping difficulty','sore throat','chest pressure','shortness of breath','runny nose']
asym = ['wheezing','anxiety','early awakening','shortness of breath at night','cough','throat irritation']

if x in cadsym:
    print("You Might Have Coronary Artery Disease")
elif x in vhdsym:
    print("You Might Have Vulvar Heart Disease")
elif x in hasym:
    print("You Might Have Heart Arrhythmia ")
elif x in mhasym:
    print("You Might Have Minor Heart Attack")
elif x in jsym:
    print("You Might Have Jaundice")    
elif x in cpsym:
    print("You Might Have Chickenpox")
elif x in msym:
    print("You Might Have Measles")
elif x in dsym:
    print("You Might Have Dengue")
elif x in masym:
    print("You Might Have Malaria")
elif x in tcsym:
    print("You Might Have Tuberculosis")
elif x in disym:
    print("You Might Have Diabetes")
elif x in pnsym:
    print("You Might Have Pneumonia")
elif x in htsym:
    print("You Might Have Hypertension")
elif x in emsym:
    print("You Might Have Emphysema")
elif x in cysym:
    print("You Might Have Cyanosis")
elif x in hysym:
    print("You Might Have Hay Fever")
elif x in ansym:
    print("You Might Have Anoxia")
elif x in hcsym:
    print("You Might Have Hypercapnia")
elif x in bcsym:
    print("You Might Have Bronchitis")
elif x in asym:
    print("You Might Have Asthama")   
else:
    print("Not Registered")

原代码存在的问题

  • 输入处理错误:input("Enter Your Symptoms: ".lower()) 错误地将提示语转成小写,应该对用户输入的内容转小写;用re.split("\\s", input1)会把多空格拆出空字符串,且无法处理用户用逗号分隔多个症状的情况。
  • 匹配逻辑错误:x是拆分后的单词列表,而疾病症状列表里的元素是完整的症状字符串(比如'chest pain'),两者类型不匹配,永远无法命中判断条件。
  • 未实现最优匹配:原代码用if-elif分支只会匹配第一个符合条件的疾病,但无法统计多症状的匹配数量,也无法找出匹配度最高的疾病。

优化后的代码

# 重构疾病数据:用字典存储疾病名称和对应的症状列表(统一转小写)
disease_symptoms = {
    "Coronary Artery Disease": ['chest pain', 'body pain', 'falling sick', 'feeling faint', 'shortness of breath'],
    "Valvular Heart Disease": ['swollen ankles', 'fainting', 'shortness of breath'],  # 修正原拼写错误fanting→fainting
    "Heart Arrhythmia": ['racing heartbeat', 'slow heartbeat', 'chest pain', 'anxiety', 'sweating'],
    "Minor Heart Attack": ['cold sweat', 'heartburn', 'sudden dizziness', 'discomfort in joints'],
    "Jaundice": ['itching', 'abdominal pain', 'weight loss', 'yellow eyes', 'yellow nails', 'vomiting'],
    "Chickenpox": ['rashes on skin', 'fever', 'sore throat', 'brown spots', 'itching'],
    "Measles": ['fever', 'runny nose', 'sneezing', 'pink eye', 'skin rash', 'diarrhoea'],
    "Dengue": ['eye pain', 'fever', 'muscle pain', 'nausea', 'joint pain', 'rash on thigh'],
    "Malaria": ['pain in muscle', 'pain in abdomen', 'night sweat', 'shivering', 'fast heart rate', 'mental confusion'],  # 修正abdomin→abdomen
    "Tuberculosis": ['chest pain', 'night sweats', 'shortness of breath', 'blood cough'],
    "Diabetes": ['increased thirst', 'frequent urination', 'hunger', 'blurred vision', 'slow healing'],  # 修正increase→increased
    "Pneumonia": ['fever', 'chills', 'sharp pain in chest', 'clammy skin'],
    "Hypertension": ['nose bleeds', 'dizziness', 'morning headaches', 'irregular heart rhythms', 'vision changes', 'buzzing in the ears'],
    "Emphysema": ['lot of mucus', 'tight chest', 'whistle sound while breathing'],
    "Cyanosis": ['bluish colour in skin', 'lips', 'nail beds'],  # 修正sikn→skin
    "Hay Fever": ['itchy', 'red and watery eyes', 'roof of mouth being itchy', 'runny or blocked nose'],  # 修正rod→roof
    "Stroke": ['unusual headache', 'memory loss', 'slurred speech', 'forgotten words', 'trouble in walking', 'trouble in moving arms', 'trouble in moving legs'],  # 修正Anoxia→Stroke(原症状更符合中风)
    "Hypercapnia": ['anxiety', 'shortness of breath', 'headache', 'daytime sleep even after sleeping a lot at night', 'daytime sluggishness'],
    "Bronchitis": ['sleeping difficulty', 'sore throat', 'chest pressure', 'shortness of breath', 'runny nose'],
    "Asthma": ['wheezing', 'anxiety', 'early awakening', 'shortness of breath at night', 'cough', 'throat irritation']  # 修正Asthama→Asthma
}

# 处理用户输入:转小写,按逗号+空格拆分症状,去除空字符串
user_input = input("Enter Your Symptoms (separate with comma and space): ").strip().lower()
user_symptoms = [symptom.strip() for symptom in user_input.split(',') if symptom.strip()]

if not user_symptoms:
    print("Please enter valid symptoms.")
else:
    # 统计每个疾病的匹配症状数量
    match_counts = {}
    for disease, symptoms in disease_symptoms.items():
        count = 0
        for user_sym in user_symptoms:
            # 检查用户输入的症状是否在疾病症状列表中(支持部分匹配?如果需要精确匹配就用==)
            if user_sym in symptoms:
                count += 1
        match_counts[disease] = count

    # 找出匹配数量最高的值
    max_count = max(match_counts.values())
    if max_count == 0:
        print("No matching disease found.")
    else:
        # 筛选出所有匹配数量等于最高值的疾病
        top_diseases = [disease for disease, count in match_counts.items() if count == max_count]
        print(f"Based on your symptoms, you might have:")
        for disease in top_diseases:
            print(f"- {disease} (matched {max_count} symptoms)")

优化说明

  1. 数据结构优化:用字典存储疾病和症状,方便遍历和维护,同时修正了原代码中的拼写错误。
  2. 输入处理优化:支持用户用逗号分隔多个症状,自动去除空格和空输入,统一转小写避免大小写不匹配。
  3. 匹配逻辑优化:统计每个疾病与用户输入症状的匹配数量,选出匹配度最高的疾病,若有多个疾病匹配数相同则全部列出。
  4. 用户体验优化:增加了输入合法性检查,输出结果更清晰,标注匹配的症状数量。

内容的提问来源于stack exchange,提问作者Echoe_matrix

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 00:35:27