我有以下字典串列,我試圖根據子句的字典是否具有將其連接到父句的“ref”屬性來提出一個連接的句子。
clause_list = [
{"id": "T1", "text": "hi"},
{"id": "T2", "text": "I'm", "ref": "T1"},
{"id": "T3", "text": "Simone", "ref": "T2"},
]
預期輸出是“hi I'm Simone”,但避免使用“hi I'm”或“I'm Simone”這樣的句子
到目前為止我嘗試的是以下內容,但無論我如何翻轉它,不想要的句子總是會被列印出來。
for c in clause_list:
for child in clause_list:
try:
if c["id"] == child["ref"] and "ref" not in c.keys():
print(c["text"], child["text"])
elif c["id"] == child["ref"] and "ref" in c.keys():
for father in clause_list:
if father["id"] == c["ref"] and "ref" not in father.keys():
print(father["text"], c["text"], child["text"])
except KeyError:
pass
uj5u.com熱心網友回復:
可能最好使用類而不是字典,但您可以輕松地將字典串列轉換為類串列。這項作業。將 dict 串列轉換為子句串列。如果沒有參考的物件,則子句具有方法 search_ref 列印部分文本,或者添加參考的物件并繼續(如果有)。如果你有 2 個物件,我不知道你到底想要什么
clause_list = [
{"id": "T1", "text": "hi"},
{"id": "T2", "text": "I'm", "ref": "T1"},
{"id": "T3", "text": "Simone", "ref": "T2"},
]
class Clause:
def __init__(self, id, text, ref:None):
self.id = id
self.text = text
self.ref = ref
def search_ref(self, Clauses, text=''):
parcialText = text ' ' self.text
for clause in Clauses:
if clause.ref == self.id:
return clause.search_ref(Clauses, parcialText)
print(parcialText)
Clauses = [Clause(id=c['id'], text=c['text'], ref=c.get('ref')) for c in clause_list]
for c in Clauses:
if c.ref is None:
c.search_ref(Clauses)
uj5u.com熱心網友回復:
因此,現在您已將資料設定為字典串列。我認為如果您將其設定為鏈表并使用一些遞回會更有幫助。也許像下面這樣。作為注釋,您需要一些東西來指示句子的開頭(我將使用“parent = True”):
clause_list = {
# ID's are the keys
'T1':{'text':"hi ", 'child':'T2','parent':True},
'T2':{'text':"I'm ", 'child':'T3'},
'T3':{'text':"Simone", 'child':None},
}
然后您的代碼可能如下所示:
# Recursive function
def print_child(child_id, clause_list):
print(clause_list[child_id]['text'])
if 'child' in clause_list[child_id]:
print_child(clause_list[child_id]['child'], clause_list)
# Main function
for id in clause_list:
if 'parent' in clause_list[id]:
print(clause_list[id]['text'])
# Recurse through the parent to find others
if 'child' in clause_list[id]:
print_child(clause_list[id]['child'], clause_list)
云肯定會被清理和優化,但這是一般要點。希望能幫助到你!
uj5u.com熱心網友回復:
使用遞回的另一種解決方案:
clause_list = [
{"id": "T1", "text": "hi"},
{"id": "T2", "text": "I'm", "ref": "T1"},
{"id": "T3", "text": "Simone", "ref": "T2"},
]
inv_dict = {d.get("ref", ""): (d["id"], d["text"]) for d in clause_list}
def get_sentence(inv_dict, key=""):
if key in inv_dict:
id_, text = inv_dict[key]
return [text] get_sentence(inv_dict, id_)
return []
print(" ".join(get_sentence(inv_dict)))
印刷:
hi I'm Simone
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/528190.html
標籤:Python字典nlp
下一篇:如何將嵌套字典與資料框合并?
