我有一個有100個條目的字典,像這樣。
d = {
'entrenched': ['the Internet is firmly entrenched in our lives.'] 。
'profoundly': ['種族主義在不同的社會領域里根深蒂固。']
}
我想回圈瀏覽字典,并根據關鍵字替換值中的一個詞。
輸出結果應該是這樣的:
d = {
'entrenched': ['the Internet is firmly en... in our lives.']。
'profoundly': ['racism is pr... entrenched within different social spheres'].
}
我試了一下這段代碼
for k,v in d.items() 。
for word in v。
if word == k:
gapped_word = word[1:] '...'。
final_sentence = v.replace(word,gapped_word )
print(final_sentence)
但沒有得到任何輸出。我也不確定最后一行應該是什么,如果我不是列印,而是用調整后的值替換原始值的話
。uj5u.com熱心網友回復:
由于每個 dictionary 專案從一個字串映射到一個串列,你應該迭代這個串列中的專案。然后,對其中的每一個專案,執行替換。此外,請注意你不必將句子分割成單詞,而只需在整個句子上執行操作。
final_d = { k: [item.replace(k, k[:2] "...") for item in v] 。for k, v in d.items()}。
凡是希望得到final_d的值:
{'entrenched': ['the Internet is firmly en... in our lives. ']。
'profoundly': ['racism is pr... entrenched within different social spheres.']}。
uj5u.com熱心網友回復:
for word in v:按整個句子進行;要想逐字得到,我們需要任選其一。- 使用
for sentence in v:thenfor word in sentence.split(); or - 使用
for sentence in v:thenif k in sentence
- 使用
- 為了把它賦值回來,我們需要替換或賦值到串列中;為了獲得賦值到陣列中的索引,我們可以使用
for i, sentence in enumerate(v),然后再v[i] = final_sentence
一般來說,在迭代程序中要小心修改字典;改變一個現有的條目應該是可以的,但是其他的東西會擾亂迭代的行程。如果你需要做更多的修改,可以用結果建立一個新的 dictionary (或者建立一個要應用的修改串列,然后在一個單獨的回圈中進行)。
uj5u.com熱心網友回復:
你可以像下面這樣使用regex:
import re
d = {
'entrenched': ['the Internet is firmly entrenched in our lives.'] 。
'profoundly': ['種族主義在不同的社會領域里根深蒂固。']。
'堅定': ['互聯網在我們的生活中根深蒂固。']。
'堅定': ['互聯網在我們的生活中根深蒂固。']。
}
{k : [re.sub(fr'{k}', f'{k[:2]}。 ...', s) for s in v] 。for k,v in d.items()}。
輸出
{'entrenched': ['the Internet is firmly en... in our lives. ']。
'profoundly': ['racism is pr... entrenched within different social spheres']。
'堅定': ['互聯網在我們的生活中根深蒂固。']。
'堅定': ['互聯網在我們的生活中是根深蒂固的。']}。
uj5u.com熱心網友回復:
假設你的字典的值總是一個包含單個字串(你的句子)的串列。你可以使用下面的代碼:
d = {key:[value[0].replace(key, key[:2] " ...") ] for key, value in d.items()}。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/327336.html
標籤:
