gpt4 book ai didi

python - 将字符串拆分为多个可能更改的变量

转载 作者:行者123 更新时间:2023-12-01 00:36:38 25 4
gpt4 key购买 nike

我有一个这样的字符串

b'***************** Winner Prediction *****************\nDate: 2019-08-27 07:00:00\nRace Key: 190827082808\nTrack Name: Mornington\nPosition Number: 8\nName: CONSIDERING\nFinal Odds: 17.3\nPool Final: 37824.7\n'

在 Python 中,我想将此字符串拆分为变量,例如:

Date =  
Race_Key =
Track_Name =
Name =
Final_Odds =
Pool_Final =

但是,字符串的格式始终相同,但值始终不同,例如,名称中可能有两个单词,因此需要适用于所有情况。

我已经尝试过:

s = re.split(r'[.?!:]+', pred0)
def search(word, sentences):
return [i for i in sentences if re.search(r'\b%s\b' % word, i)]

但运气不佳。

最佳答案

您可以拆分字符串并将其解析为如下所示的字典:

s = s.decode() #decode the byte string
n = s.split('\n')[1:-1] #split the string, drop the Winner Prediction and resulting last empty list entry

keys = [key.split(': ')[0].replace(': ','') for key in n] #get keys
vals = [val.split(': ')[1] for val in n] #get values for keys

results = dict(zip(keys,vals)) #store in dict

结果:

Date             2019-08-27 07:00:00
Race Key 190827082808
Track Name Mornington
Position Number 8
Name CONSIDERING
Final Odds 17.3
Pool Final 37824.7

关于python - 将字符串拆分为多个可能更改的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57701605/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com