我想通过python字典从语音输入迭代一些字符串,其中包含一个,两个或多个单词在关键,并将字符串添加到列表中,如果存在于dict键。我知道如何将字符串(voiceinput
)添加到新列表(fruit_cart
),如果它只包含dict键(dict_fruit
)中的一个单词并迭代其值,如下所示:
# one word only of dict keys
dict_fruit = {"apple": 2, "melon": 6, "mango": 3, "banana": 4, "grape": 5}
voiceinput = 'I want 2 Melons 3 apples 1 mango 4 grapes and 1 banana'
def show_order(cart, quantity, price, gross_price):
print(); print("PYTHON FRUIT STORE".center(55, " "))
print("=" * 55); print(f"{'# ':<5}{'Item':<15}{'Item':<10}{'Order':<10}{'Order':>8}")
print(f"{' ':<5}{'Name':<15}{'Price':<10}{'Quantity':<10}{'Price':>8}"); print("-" * 55)
total_price = 0
for idx, item in enumerate(cart):
print(f"{idx + 1:<5}{item:<15}{'$':<2}{price[idx]:>2}{quantity[idx]:^15}{'$':>3} {gross_price[idx]:.2f}")
total_price = total_price + gross_price[idx]
tax = 10 if total_price > 4.99 else 11
vat = total_price * tax / 100
final_price = total_price + vat
print("-" * 55); print("tttttTotal Price ", f"{'$':<1} {total_price:.2f}")
print(f"tttttVAT {tax}% ", f"{'$':<1} {vat:.2f}")
print("tttttFinal Price ", f"{'$':<1} {final_price:.2f}"); print()
print(" Thank You ".center(55, "="))
return final_price
def order_process(userinput):
userlist = [char.removesuffix("s") for char in userinput.lower().split()]
fruit_cart = [item for item in userlist if item in dict_fruit]
fruit_quantity = [int(num) for num in userlist if num.isdigit() and num != '0']
if len(fruit_cart) != len(fruit_quantity) or len(fruit_quantity) == 0 or len(fruit_cart) == 0: return exit()
fruit_price = [dict_fruit[item] for item in fruit_cart]
gross_price = [qty * prc for qty, prc in zip(fruit_quantity, fruit_price)]
return show_order(fruit_cart, fruit_quantity, fruit_price, gross_price)
order_process(voiceinput) if any(word in voiceinput for word in dict_fruit) else exit()
对于这两个单词,我尝试将第一个单词和第二个单词拆分为单独的2个列表(first_word
和second_word
)并使用元组(fruit_color
和fruit_names
)迭代它们,然后在末尾(join_word
和fruit_cart
)加入它们,但似乎这不是优雅的方式或解决方案,因为它只适用于2个单词:
# two words only of dict keys
dict_fruit = {"red apple": 2, "green apple": 2, "black grape": 5}
fruit_color = ('red', 'green', 'black')
fruit_names = ('apple', 'grape')
voiceinput = 'I want 3 green Apples 2 red apples and 1 black grape'
def order_process(userinput):
userlist = [char.removesuffix("s") for char in userinput.lower().split()]
first_word = [word for word in userlist if word in fruit_color]
second_word = [word for word in userlist if word in fruit_names]
if len(first_word) != len(second_word): return exit()
join_word = [word for pair in zip(first_word, second_word) for word in pair]
fruit_cart = [' '.join(word) for word in zip(join_word[0::2], join_word[1::2])]
fruit_quantity = [int(num) for num in userlist if num.isdigit() and num != '0']
if len(fruit_cart) != len(fruit_quantity) or len(fruit_quantity) == 0 or len(fruit_cart) == 0: return exit()
elif not any(word in fruit_cart for word in dict_fruit): return exit()
fruit_price = [dict_fruit[item] for item in fruit_cart]
gross_price = [qty * prc for qty, prc in zip(fruit_quantity, fruit_price)]
return show_order(fruit_cart, fruit_quantity, fruit_price, gross_price)
order_process(voiceinput) if any(word in voiceinput for word in dict_fruit) else exit()
如果字符串和字典键包含1个、2个或更多这样的单词怎么办:
dict_fruit = {"red apple": 2, "green apple": 1, "melon": 6, "mango": 3, "banana": 4, "black grape": 5}
voiceinput = 'I want 2 red Apples 3 mangos 1 melon and 4 black grapes'
然后添加字符串(voiceinput
),如果它存在于dict键(dict_fruit
)中,反之亦然,到一个新的列表(fruit_cart
),如下所示:
fruit_cart = ['red apple', 'mango', 'melon', 'black grape']
我知道代码很乱,顺便说一下,我是python的新手。
这是一个适合正则表达式(regex)的工作。
对于dict_fruit = {"red apple": 2, "green apple": 1, "melon": 6, "mango": 3, "banana": 4, "black grape": 5}
,
合适的正则表达式是(d+) (red apple|green apple|melon|mango|banana|black grape)
,
可以用f"(\d+) ({'|'.join(dict_fruit.keys())})"
构建。
import re
dict_fruit = {"red apple": 2, "green apple": 1, "melon": 6, "mango": 3, "banana": 4, "black grape": 5}
voiceinput = 'I want 1 apple 2 red Apples 3 mangos 1 melon and 4 black grapes'
# dict_fruit = {"red apple": 2, "green apple": 1, "melon": 6, "mango": 3, "banana": 4, "black grape": 5}
# voiceinput = 'I want 1 apple 2 red Apples 3 mangos 1 melon and 4 black grapes'
# dict_fruit = {"apple": 1, "red apple": 2, "green apple": 1, "melon": 6, "mango": 3, "banana": 4, "black grape": 5}
# voiceinput = 'I want 1 apple 2 red Apples 3 mangos 1 melon and 4 black grapes'
def show_order(cart, quantity, price, gross_price):
print(); print("PYTHON FRUIT STORE".center(55, " "))
print("=" * 55); print(f"{'# ':<5}{'Item':<15}{'Item':<10}{'Order':<10}{'Order':>8}")
print(f"{' ':<5}{'Name':<15}{'Price':<10}{'Quantity':<10}{'Price':>8}"); print("-" * 55)
total_price = 0
for idx, item in enumerate(cart):
print(f"{idx + 1:<5}{item:<15}{'$':<2}{price[idx]:>2}{quantity[idx]:^15}{'$':>3} {gross_price[idx]:.2f}")
total_price = total_price + gross_price[idx]
tax = 10 if total_price > 4.99 else 11
vat = total_price * tax / 100
final_price = total_price + vat
print("-" * 55); print("tttttTotal Price ", f"{'$':<1} {total_price:.2f}")
print(f"tttttVAT {tax}% ", f"{'$':<1} {vat:.2f}")
print("tttttFinal Price ", f"{'$':<1} {final_price:.2f}"); print()
print(" Thank You ".center(55, "="))
return final_price
def order_process(userinput):
matches = re.findall(f"(\d+) ({'|'.join(dict_fruit.keys())})", userinput.lower())
fruit_quantity, fruit_cart = zip(*((int(quantity), fruit) for quantity, fruit in matches))
fruit_price = [dict_fruit[item] for item in fruit_cart]
gross_price = [qty * prc for qty, prc in zip(fruit_quantity, fruit_price)]
return show_order(fruit_cart, fruit_quantity, fruit_price, gross_price)
order_process(voiceinput) if any(word in voiceinput for word in dict_fruit) else exit()
这个解决方法通过使用嵌套的for循环迭代输入来解决字典中1,2或更多单词的问题,并检查每个分裂到字典中的单词连接的所有可能性:
dict_fruit = {"red apple": 2, "green apple": 1, "melon": 6, "mango": 3, "banana": 4, "black grape": 5}
voiceinput = 'I want 2 red Apples 3 mangos 1 melon and 4 black grapes'
def show_order(cart, quantity, price, gross_price):
print(); print("PYTHON FRUIT STORE".center(55, " "))
print("=" * 55); print(f"{'# ':<5}{'Item':<15}{'Item':<10}{'Order':<10}{'Order':>8}")
print(f"{' ':<5}{'Name':<15}{'Price':<10}{'Quantity':<10}{'Price':>8}"); print("-" * 55)
total_price = 0
for idx, item in enumerate(cart):
print(f"{idx + 1:<5}{item:<15}{'$':<2}{price[idx]:>2}{quantity[idx]:^15}{'$':>3} {gross_price[idx]:.2f}")
total_price = total_price + gross_price[idx]
tax = 10 if total_price > 4.99 else 11
vat = total_price * tax / 100
final_price = total_price + vat
print("-" * 55); print("tttttTotal Price ", f"{'$':<1} {total_price:.2f}")
print(f"tttttVAT {tax}% ", f"{'$':<1} {vat:.2f}")
print("tttttFinal Price ", f"{'$':<1} {final_price:.2f}"); print()
print(" Thank You ".center(55, "="))
return final_price
def order_process(userinput):
userlist = [char.removesuffix("s") for char in userinput.lower().split()]
fruit_cart = [
' '.join(userlist[i:i+j])
for i in range(len(userlist))
for j in range(1, len(userlist) - i + 1)
if ' '.join(userlist[i:i+j]) in dict_fruit
]
fruit_quantity = [int(num) for num in userlist if num.isdigit() and num != '0']
if len(fruit_cart) != len(fruit_quantity) or len(fruit_quantity) == 0 or len(fruit_cart) == 0: return exit()
elif not any(word in fruit_cart for word in dict_fruit): return exit()
fruit_price = [dict_fruit[item] for item in fruit_cart]
gross_price = [qty * prc for qty, prc in zip(fruit_quantity, fruit_price)]
return show_order(fruit_cart, fruit_quantity, fruit_price, gross_price)
order_process(voiceinput) if any(word in voiceinput for word in dict_fruit) else exit()
但是,如果在输入中有一个单词包含两个单词的单词,则此代码结束,因为fruit_cart
和fruit_quantity
的长度不相同,因为fruit_cart
中没有添加一个单词:
dict_fruit = {"red apple": 2, "green apple": 1, "melon": 6, "mango": 3, "banana": 4, "black grape": 5}
voiceinput = 'I want 1 apple 2 red Apples 3 mangos 1 melon and 4 black grapes'
# userlist = ['i', 'want', '1', 'apple', '2', 'red', 'apple', '3', 'mango', '1', 'melon', 'and', '4', 'black', 'grape']
# fruit_cart = ['red apple', 'mango', 'melon', 'black grape']
# fruit_quantity = [1, 2, 3, 1, 4]
尽管单词已经被添加到字典中,例如'apple':
dict_fruit = {"apple": 1, "red apple": 2, "green apple": 1, "melon": 6, "mango": 3, "banana": 4, "black grape": 5}
voiceinput = 'I want 1 apple 2 red Apples 3 mangos 1 melon and 4 black grapes'
# userlist = ['i', 'want', '1', 'apple', '2', 'red', 'apple', '3', 'mango', '1', 'melon', 'and', '4', 'black', 'grape']
# fruit_cart = ['apple', 'red apple', 'apple', 'mango', 'melon', 'black grape']
# fruit_quantity = [1, 2, 3, 1, 4]