我有一个结构:
{
"content": "Name 1",
"name": "directory",
"decendent": [
{
"content": "Name 2",
"name": "subdirectory",
"decendent": None
},
{
"content": "Name 3",
"name": "subdirectory_two",
"decendent": [
{
"content": "Name 4",
"name": "subsubdirectory",
"decendent": None
}
]
}
]
}
我必须查找在搜索字段中输入的单词序列:
<form id="tfnewsearch" method="get" action="/help/search">
<input type="text" class="tftextinput" name="q" size="21" maxlength="120">
<input type="submit" value="Search" class="tfbutton">
</form>
如果我找到了 - 将它们添加到
[
{
"content": "The sought content",
"phrase": "the sought phrase",
"name": "unique name"
}, ...
]
对于每一个发现的巧合。
例如: 如果我寻找“我有”,我应该得到:
[
{
"content": "I have a good day",
"phrase": "I have",
"name": "subdirectory",
},
{
"content": "While I have several ways to do it",
"phrase": "I have",
"name": "subdirectory2"
},
{
"content": "When I had it",
"phrase": "I have",
"name": "subdirectory3"
},
]
如果我要在搜索过程中使用词法分析器(如 pymorhph2)更改此短语(例如:“have”、“had”),如何使用递归在 Python 中实现它?
提前致谢!
最佳答案
我不知道 pymorph2,但你可以这样做:
def f1(a, s):
if s in a["contents"]:
a["phrase"] = s
for b in a["descendent"]:
f(b, s)
参数 a 是您的主要词典,s 要查找的短语。
但是,如果您再次调用 f,它将清除之前的值。如果这不是您想要的,您可以考虑替代,例如:
def f2(a, s):
if s in a["contents"]:
if "phrase" not in a:
a["phrase"] = [s]
else:
a["phrase"].append(s)
for b in a["descendent"]:
f(b, s)
如果您还想返回匹配字典的列表:
def f3(a, s):
r = []
if s in a["contents"]:
if "phrase" not in a:
a["phrase"] = [s]
else:
a["phrase"].append(s)
r.append(a)
for b in a["descendent"]:
r += f(b, s)
return r
如果你想复制输出列表中的数据而不是只引用原始字典,你可以将 r.append(a)
替换为,例如
r.append({k: a[k] for k in ("content", "phrase", "name")})
关于python - 如何在字典中查找短语?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29888261/