Hello, I am currently writing a menu that has a search bar. The tree loads from a Json and I want to be able to use word association to search my results. AKA if I search oven, kitchen will come up. If I search couch, Living room will come up. I haven't written any code for this yet. As I don't know where to start. I would assume it would be creating an array in all of my Json objects called associatedWords and then searching across them, rather than just the name. If anybody has done anything similar in the past your help would be appreciated. Just to clarify I already have a working menu that reacts to what I seach, im just unsure of where/ how to impliment the array searching.
Can you post your existing code? I would be easier to suggest how you can add on to you existing solution if we see what you already have.
How complex/complete do you want this to be ?
If what you have in mind is a simple and small dictionary of related words, it shouldn't be too hard.
For anything more advanced... I'm sure there are APIs for it. Because you're entering NLP territory and frankly if it's not your field... don't.
Many databases have a "full text search" specialty index type or set of conditional functions. I'd use that--let the database do the heavy lifting.
def transform(self, value, quality, timestamp):
search = value['search'] or ''
tree = value['tree']
userRoles = value['userRoles']
currentViewPath = self.view.custom.currentViewPath
logger1 = system.util.getLogger("Logger1")
logger1.info("Current view path " + str(currentViewPath))
def checkIfCurrentPathInItem(item):
if item.has_key('target'):
if item['target']['path'] == currentViewPath: return True
if item.has_key('children'):
# print item['label'] + ' has children'
for item in item['children']:
if checkIfCurrentPathInItem(item): return True
return False
def translateItem(item, index, parentIndices):
targetPath = item["target"]["path"] if item.has_key("target") else None
isSearchPath = search.lower() in item["label"].lower()
isCurrentInPath = checkIfCurrentPathInItem(item)
return {
"label": item["label"],
"data": {
"target": item["target"] if item.has_key("target") else '',
"display": isSearchPath or isCurrentInPath,
'index': parentIndices + [str(index)]
},
"expanded": isCurrentInPath,
"items": [],
"icon": {
"path": item["icon"] if item.has_key("icon") else '',
"color": ""
}
}
def buildTreeLevel(items, parent):
translatedItems = []
indexCounter = 0
for item in items:
# system.perspective.print(str(item['enabled']))
if not item.has_key('enabled') or (item.has_key('enabled') and item['enabled']):
translatedItem = translateItem(item, indexCounter, parent["data"]["index"])
# Call a function to find out if the currentViewPath is contained within this item or its children ONLY if this item is a folder
if item.has_key('children'):
translatedItem['items'] = buildTreeLevel(item['children'], translatedItem)
for i in range(len(translatedItem['items'])):
if translatedItem['items'][i]['data']['display']:
translatedItem['data']['display'] = True
if translatedItem['items'][i]['expanded']:
translatedItem['expanded'] = True
if translatedItem['data']['display']:
if search != '': translatedItem['expanded'] = True
translatedItems.append(translatedItem)
indexCounter += 1
return translatedItems
hierarchyRoot = {"data": {"index": []}}
return buildTreeLevel(tree, hierarchyRoot)
This is the script I am using to build the tree from the json. I am not using a menu tree, but a normal tree. I want to have it dynamic as I need to be able to load any json I want. I want to have my seach not only search across the name, but across some array associatedNames which will be stored in the json.
^^This is the property binding on the text property of my search bar.^^
Here is how I upload my file to the custom session prop tree
print(self.session.props.auth.user.id)
userNameIn = self.session.props.auth.user.userName
if(userNameIn == ("admin")):
jsonString = system.file.readFileAsString("C:\\Temp\\Json.txt")
else :
jsonString = system.file.readFileAsString("C:\\Temp\\JsonNormal.txt")
#this should use a switch statement, but i cant seem to figure out how it works, as not python, not java, not c and not c#
self.session.custom.tree = system.util.jsonDecode(jsonString)
I simply want an array of associated word to be pulled from the json and compared against the search String that my user creates. Nothing too complex I don't think.
Just a few tips/notes:
dicts
have aget
method that takes an optionaldefault
parameter. So instead of writing
item["icon"] if item.has_key("icon") else ''
you can write
item.get('icon', '')
- There's this in your code:
'index': parentIndices + [str(index)]
It looks weird to me that an index would be cast to a string - You should probably move the whole thing to a library function instead of doing everything in a transform. When you're defining functions or doing recursion in a transform, it's usually a sign that there's too much going on for a transform.
If all you want to do is check if a term is in a list... I fail to see the issue.
What exactly is the problem ?