我想更改pattern它,使其不僅匹配具有單位和數量的字串,而且還匹配單獨的單位。例如,我希望它也匹配“立方體”,即使它沒有列出數量。同樣,如果字串只有金額而不是單位,我希望它也單獨匹配金額。目前,回傳的輸出是
['1.0', '0.07', '32.0', '0.12', '1.01', 'cubes', '2']
我希望輸出如下:
['1.0', '0.07', '32.0', '0.12', '1.01', '1.0', '2.0']
這是代碼:
list_of_texts = ["1oz", "2ml", "4cup", "1 wedge","2 slices", "cubes", "2"]
pattern = r"(^[\d -/] )(oz|ml|cl|tsp|teaspoon|teaspoons|tea spoon|tbsp|tablespoon|tablespoons|table spoon|cup|cups|qt|quart|quarts|drop|drop|shot|shots|cube|cubes|dash|dashes|l|L|liters|Liters|wedge|wedges|pint|pints|slice|slices|twist of|top up|small bottle)"
new_list = []
for text in list_of_texts:
re_result = re.search(pattern, text)
if re_result:
amount = re_result.group(1).strip()
unit = re_result.group(2).strip()
print(amount)
print(unit)
if "-" in amount:
ranged = True
else:
ranged = False
amount = re.sub(r"(\d) (/\d)",r"\1\2",amount)
amount = amount.replace("-"," ").replace(" "," ").strip()
amount = re.sub(r"[ ] "," ",amount)
amount_in_dec = frac_to_dec_converter(amount.split(" "))
amount = np.sum(amount_in_dec)
if ranged:
to_oz = (amount*liquid_units[unit])/2
else:
to_oz = amount*liquid_units[unit]
new_list.append(str(round(to_oz,2)))
else:
new_list.append(text)
注意:我有一本包含轉換單位的字典
uj5u.com熱心網友回復:
*通過使用而不是使數字成為可選的 。然后,如果第一個捕獲組為空,則將其視為1.0.
pattern = r"(^[\d -/]*)(oz|ml|cl|tsp|teaspoon|teaspoons|tea spoon|tbsp|tablespoon|tablespoons|table spoon|cup|cups|qt|quart|quarts|drop|drop|shot|shots|cube|cubes|dash|dashes|l|L|liters|Liters|wedge|wedges|pint|pints|slice|slices|twist of|top up|small bottle)"
for text in list_of_texts:
re_result = re.search(pattern, text)
if re_result:
amount = re_result.group(1).strip()
if amount == '':
amount = '1.0'
unit = re_result.group(2).strip()
print(amount)
print(unit)
# rest of your code
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/466802.html
