【问题标题】:How to look through a phrase in a dictionary?如何查看字典中的短语?
【发布时间】:2015-07-05 11:08:59
【问题描述】:

我有一个结构:

{
    "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 中实现它?

提前致谢!

【问题讨论】:

  • 我已将其添加到说明中
  • 已修复。你可以再读一遍。

标签: python django algorithm search recursion


【解决方案1】:

我不知道 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")})

【讨论】:

  • 但是如果我想返回一个字典列表呢?例如: res = [res] + f(d2, name) if res: return res
  • @paus 已编辑。您想返回所有匹配字典的列表,还是只返回包含所需数据的新字典?我的意思是,按原样, f3 不会删除后代,但这应该不是问题。
  • 只有新鲜的字典,只有需要的数据,没有后代,我认为。因为在我的情况下,内容 - 是 html 文件的内容,它的大小可能很大。
  • @paud 注意它们只是指针,在这个过程中没有任何重复。如果您不构建新的字典(您只在列表中放置指针,没有新数据),则重复次数会更少。如果您以后想在主结构中修改它们,这将是必要的。这真的取决于你想做什么。
  • 我想在搜索结果中列出它。所以我真的不知道这个过程中是否需要修改,但是重复数据可能会很昂贵。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-08-21
  • 1970-01-01
  • 2018-01-22
  • 2017-03-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多