簡體   English   中英

將值“附加”到特定鍵的字典中

[英]'Append' a value to a dictionary for a specific key

我想在給定句子的字典中存儲和分組不同的實體,它們在句子中的索引和實體類型。

我有一個像這樣的字符串:

text = "My name is David and I live in Miami, but I was born in San Francisco"

我想通過索引替換此字符串中的實體 PERSON 和 LOCATION ,並提供以下信息。

entities = ['PERSON','LOCATION','LOCATION']
start = [11,31,56]
end = [16,36,69]

我試過這個:

def replace_by_index(text: str, entities: List ,start: List,end: List,):
    entities_dict = {}
    tmp = []
    for ent,st,ed in zip(entities,start,end):
        entities_dict[ent] = text[st:ed]
        
    return entities_dict

這顯然不起作用......因為第一個位置被覆蓋了!

{'PERSON': 'David', 'LOCATION': 'San Francisco'}

我不想將實體的值用於邏輯:語句如下:

if ent == 'PERSON':
   #logic

這在這種情況下不起作用:我想要一些可以像這樣工作的東西:

def replace_by_index(text: str, entities: List ,start: List,end: List,):
    entities_dict = {}
    tmp = []
    for ent,st,ed in zip(entities,start,end):
        entities_dict[ent] = tmp.append(text[st:ed])
        
    return entities_dict

這個返回:

{'PERSON': None, 'LOCATION': None}

所需 OUTPUT:

{'PERSON': ['David'], 'LOCATION': ['Miami','San Francisco']}

這是我用來解決問題的方法,我的問題是在給定索引的情況下同時替換所有實體。 如果我有這本字典,我的下一步是用string.replace()將單詞替換為它們各自的實體。 也許有更好的方法?

最終目標是得到一個字符串,如:

“我的名字是 PERSON_0,我住在 LOCATION_0,但我出生在 LOCATION_2”

嘗試這個

r = entities_dic.get(ent,[])
r.append(text[st:ed])
entities_dict[ent] =  r

更好的方法是創建字典

(開始,結束):實體

循環遍歷您的句子標記。

將 text[start, end] 替換為 dic[(start, end)] 其中 dict 是您創建的內容。

我同意 InfoLearner 的觀點。 稍后設置字典比 append 更容易。 這是另一種方法。

text = "My name is David and I live in Miami, but I was born in San Francisco"
entities = ['PERSON', 'LOCATION', 'LOCATION']
start = [11, 31, 56]
end = [16, 36, 69]
entities_dict = {ent: [] for ent in set(entities)}  # set up dictionary
for st, ed, ent in zip(start, end, entities):
    entities_dict[ent].append(text[st:ed])  # append the slice to the item with the appropriate entity
print(entities_dict)

Output:

{'LOCATION': ['Miami', 'San Francisco'], 'PERSON': ['David']}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM