[英]Accessing nested dictionary in json from python file
我有一個 intent.json 文件
{"intents": [
{"tag": "greeting",
"patterns": ["Hi there", "How are you", "Is anyone there?", "Hello", "Good day"],
"responses": ["Hello, thanks for asking", "Good to see you again", "Hi there, how can I help?"],
"context": [""]
},
{"tag": "goodbye",
"patterns": ["Bye", "See you later", "Goodbye", "Nice chatting to you, bye", "Till next time"],
"responses": ["See you!", "Have a nice day", "Bye! Come back again soon."],
"context": [""]
}
]
}
我有 python 文件,其中以下函數獲取句子的意圖,輸出如下
classify_local('Hello, good day!')
輸出為
['greeting']
現在我想獲取與標簽問候相對應的響應。 我怎樣才能做到這一點?
這里有很多可能的漏洞,但考慮到預期的輸出,這應該可以找出句子給出的有限 I/O 的意圖類型。
import string
def classify_local(text):
# Separate out the phrases of the input text
# "Hello, good day!" --> ['hello', 'good day']
phrases = [
s.translate(s.maketrans("", "", string.punctuation)).strip().lower()
for s in text.split(",")
]
# Find tags where all phrases are in patterns
return [
i["tag"]
for i in intents_json["intents"]
if all(j in [k.lower() for k in i["patterns"]] for j in phrases)
]
classify_local("Hello, good day!")
如果您想要更柔和的匹配,請將返回中的all
替換為any
,但這在更廣泛的數據集中不太可能正確。
請記住,當針對較大的數據集解析書面句子時,這一切都會很快崩潰。
你可以使用正則表達式:
import re
my_json = {"intents": [
{"tag": "greeting",
"patterns": ["Hi there", "How are you", "Is anyone there?", "Hello", "Good day"],
"responses": ["Hello, thanks for asking", "Good to see you again", "Hi there, how can I help?"],
"context": [""]
},
{"tag": "goodbye",
"patterns": ["Bye", "See you later", "Goodbye", "Nice chatting to you, bye", "Till next time"],
"responses": ["See you!", "Have a nice day", "Bye! Come back again soon."],
"context": [""]}]}
pattern_tag = {'|'.join(d["patterns"]): d['tag'] for d in my_json["intents"]}
def classify_local(my_strig):
for p, t in pattern_tag.items():
if re.search(p, my_strig):
return t
classify_local('Hello, good day!')
輸出:
'greeting'
從您的 json 文件中讀取:
import json
with open('intent.json') as f:
my_json = json.load(f)
如果您只想要標簽greeting
所有響應中的第一個響應,那么它是,
json_value = {
"intents": [
{
"tag": "greeting",
"patterns": ["Hi there", "How are you", "Is anyone there?", "Hello", "Good day"],
"responses": ["Hello, thanks for asking", "Good to see you again", "Hi there, how can I help?"],
"context": [""]
},
{
"tag": "goodbye",
"patterns": ["Bye", "See you later", "Goodbye", "Nice chatting to you, bye", "Till next time"],
"responses": ["See you!", "Have a nice day", "Bye! Come back again soon."],
"context": [""]
}
]
}
for intent in json_value['intents']:
if intent['tag'] == 'greeting':
response = intent['responses'][0]
print(response)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.