你可以使用正則表達式來分割任何數字。然後,在結果列表中,分割以獲取單詞及其含義。將它存儲到您的字典!
>>> terms
'1 Alliteration- the repetition of a speech sound in a sequence of nearby words 2 Term - definition...'
>>> d={}
>>> import re
>>> dict(l.strip().split('-') for l in re.split('[0-9]',terms) if l)
{'Alliteration': ' the repetition of a speech sound in a sequence of nearby words', 'Term ': ' definition...'}
>>> d
{' Alliteration': ' the repetition of a speech sound in a sequence of nearby words ', ' Term ': ' definition...'}
也就是說,
>>> re.split('[0-9]',terms)
['', ' Alliteration- the repetition of a speech sound in a sequence of nearby words ', ' Term - definition...']
>>> [l for l in re.split('[0-9]',terms)]
['', ' Alliteration- the repetition of a speech sound in a sequence of nearby words ', ' Term - definition...']
>>> [l for l in re.split('[0-9]',terms) if l]
[' Alliteration- the repetition of a speech sound in a sequence of nearby words ', ' Term - definition...']
>>> [l.strip().split('-') for l in re.split('[0-9]',terms) if l]
[['Alliteration', ' the repetition of a speech sound in a sequence of nearby words'], ['Term ', ' definition...']]
>>> dict(l.strip().split('-') for l in re.split('[0-9]',terms) if l)
{'Alliteration': ' the repetition of a speech sound in a sequence of nearby words', 'Term ': ' definition...'}
不使用列表解析,
>>> for l in re.split('[0-9]',terms):
... if l:
... key,value = l.strip().split('-')
... d[key]=value
...
在這裏,而不是d[key]=value
可以使用d[key]=d.get(key,'')+value+'\n'
如果條件一個字可以有多種含義!
@Justin O'Brien嘗試dict1 = {a.split(「 - 」)[0] .strip():a.split(「 - 」)[1] .strip()in str2 if' - 'in a} – jimidime
這個工作,謝謝 –
雖然這段代碼可能會回答這個問題,提供關於**如何**和**爲什麼**解決問題的額外上下文將提高答案的長期價值。 – Alexander