Python 提取字符串中的度量值 - 正則表達式實作
您可以使用正則表達式來提取字符串中的子串。以下是一個示例函數可以實現您的需求:
import re
def extract_degrees(string):
pattern = r'(正裝度|變裝度)\s*(\d+)'
matches = re.findall(pattern, string)
degrees = {}
for match in matches:
degree_type, degree_value = match
degrees[degree_type] = int(degree_value)
return degrees
# 測試函數
string = '正裝度20、變裝度30'
degrees = extract_degrees(string)
print(degrees) # 輸出: {'正裝度': 20, '變裝度': 30}
在這個示例中,我們使用正則表達式 (正裝度|變裝度)\s*(\d+) 來匹配字符串中的子串。其中 (正裝度|變裝度) 表示匹配 '正裝度' 或 '變裝度' 這兩個詞,\s* 表示匹配零個或多個空格,(\d+) 表示匹配一個或多個數字。然後,使用 re.findall() 函數找到所有匹配的子串,並將其存儲在 matches 列表中。最後,將匹配的子串提取出來,存儲在一個字典 degrees 中,其中鍵是度量的類型,值是度量的數值。
原文地址: https://www.cveoy.top/t/topic/kcu 著作权归作者所有。请勿转载和采集!