将字符串拆分为多个变量

2024-09-28 23:27:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一根这样的绳子

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)]

但是那里没有运气。你知道吗


Tags: key字符串nameresearchsentenceswordfinal
3条回答

您可以使用以下选项:

return [line.split(":", 1)[-1].strip() for line in s.splitlines()[1:]]

这将返回(作为示例输入):

['2019-08-27 07:00:00', '190827082808', 'Mornington', '8', 'CONSIDERING', '17.3', '37824.7']

您可以拆分字符串并将其解析为一个dict,如下所示:

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

也许你可以试试这个:

p = 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'
out = p.split(b"\n")[:-1][1:]
d = {}
for i in out:
    temp = i.split(b":")
    key = temp[0].decode()
    value = temp[1].strip().decode()
    d[key] = value
output would be:
{'Date': '2019-08-27 07',
 'Race Key': '190827082808',
 'Track Name': 'Mornington',
 'Position Number': '8',
 'Name': 'CONSIDERING',
 'Final Odds': '17.3',
 'Pool Final': '37824.7'}

相关问题 更多 >