Создание приговора на основе условий - PullRequest
0 голосов
/ 06 августа 2020

Это входной Dict, где я вывел и сгенерировал предложение

Вход

indexes={'Laptops':'1','Mob':'2','Cars':'3','Bus':4}
    Notes={
 

   
    'indexs':[1,3],
    'Laptops':[
        "dell","asus","acer"
    ],
    'Mob':[
        "mi","realme"
    ],
   'Bus':[
     "aB"
 
   ],
    'Cars':["Not found"
         ]

}

Создал генератор предложений для генерации предложения:

def SenGen(alpha,beta):
    for a,b in alpha.items():
        for c,d in beta.items():
            if c in a:
                print(f"{a} are ", end="")
                for i, e in enumerate(b):
                    if i == len(b)-1:
                        print(f"and {e}. ", end="")
                    elif i == len(d)-2:
                        print(f"{e} ", end="")
                    else:
                        print(f"{e}, ", end="") 

с помощью этой функции я сгенерировал предложение

SenGen(Notes,indexes)

output

Laptops are dell, asus, and acer. Mob are mi, and realme. Bus are and aB. Cars are and not found. 

В приведенном выше предложении в шине есть только одно значение, то есть aB, но в сгенерированном я получил его как 'bus are and aB', а для автомобилей это сгенерировано как "cars not found"

Но ожидаемый результат должен быть таким, как показано ниже:

Laptops are dell, asus, and acer. Mob are mi, and realme. Bus is aB. Cars are not found.

где Bus is aB и машин нет

Пожалуйста, помогите с кодом и как импровизировать мой код для случая 1.

случай 2:

input indexes={'Laptops':'1','Mob':'2','Cars':'3','Bus':4}

Notes={
    
    'indexs':[1,3],
    'Laptops':[
        "dell","asus","acer"
    ],
    'Mob':[
        "mi","realme"
    ],
   'Bus':[
     "aB"
 
   ],
    'Cars':[
         ]

}

в случае 2, у меня значение автомобилей пусто, и вывод показан ниже

вывод

Laptops are dell, asus, and acer. Mob are mi, and realme. Bus are and aB. Cars are 

Желаемый вывод:

Laptops are dell, asus, and acer. Mob are mi, and realme. Bus is aB. Cars are not found.

Пожалуйста, помогите с кодом и как импровизировать мой код для случая 2.

я устал от следующих случаев:

1.if i == len(b)==1:
                            
    print(f" is {e} ", end="")

2.if i == len(b)==0:
                            
    print(f" is {e} ", end="")
3.if i == len(b)<1:
                            
    print(f" is {e} ", end="")
4.if i == len(b)>1:
                            
    print(f" is {e} ", end="")

                

нет изменений в моем выводе мой выход остался таким же, как показано ниже.

Laptops are dell, asus, and acer. Mob are mi, and realme. Bus are and aB. Cars are

1 Ответ

0 голосов
/ 07 августа 2020

Что вы сделали неправильно, так это то, что вы никогда не принимали во внимание некоторые случаи. Вот модифицированная версия вашей функции; Я добавил несколько комментариев, чтобы объяснить случаи, которые вы забыли:

def SenGen(alpha,beta):
    for a,b in alpha.items():
        for c,d in beta.items():
            if c in a:
                # in case the value of some key is empty (like Cars in your case)
                if b == []:
                    print(f"{a} are not found.")
                if len(b) > 1:
                    print(f"{a} are ", end="")
                for i, e in enumerate(b):
                    # in case the key has only one value, which might be "Not found" or some other value
                    if len(b) == 1:
                        if "Not found" in b:
                            print(f"{a} are {e}. ", end="")
                        else:
                            print(f"{a} is {e}. ", end = "")
                    # in case the key has more than one value
                    else:
                        if i == len(b)-1:
                            print(f"and {e}. ", end="")
                        elif i == len(d)-2:
                            print(f"{e} ", end="")
                        else:
                            print(f"{e}, ", end="")
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...