【问题标题】:How do I make my search case insensitive?如何使我的搜索不区分大小写?
【发布时间】:2020-01-30 06:08:32
【问题描述】:

我有一个搜索几个数据库的网络应用程序,保存的一些数据是大写的,一些是大小写混合的,但是在搜索关键字时,我希望它忽略大小写,只显示结果匹配单词。例如,我想搜索“document_reference”而不必编写正确的保存方式,即“Document_Reference”

我被告知要在我的索引中添加不区分大小写的功能,但我不确定该做什么或在那里添加, 我试过这个(在 whoosh 文档中找到)

class CaseSensitivizer(analysis.Filter):
    def __call__(self, tokens):
        for t in tokens:
            yield t
            if t.mode == "index":
                low = t.text.lower()
                if low != t.text:
                    t.text = low
                    yield t

这就是我的索引和查询解析器的样子

def open_index(indexDirectory):
    # open index and return a idex object
    ix = index.open_dir(indexDirectory)
    return ix


def search_index(srch, ix):
    #  Search the index and print results
    #  ix = open_index(indexDirectory)
    results = ''
    lst = []
    qp = MultifieldParser(['Text', 'colname',
        'tblname', 'Length', 'DataType', 'tag_name'],
        schema=ix.schema, group=qparser.OrGroup)
    # qp = QueryParser('Text', schema=ix.schema)
    q = qp.parse(srch)
    with ix.searcher() as s:
        results = s.search(q, limit=None)
        for r in results:
            print('\n', r)
            lst.append(r.fields())
        if(DEBUG):
            print('Search Results:\n', lst)
            print('\nFinished in search.py')
        return lst

目前它只会给出与我在搜索栏中输入的内容完全匹配的结果,所以如果我输入“文档”但源实际上存储为“文档”,我不会得到任何结果

【问题讨论】:

    标签: python flask indexing case-insensitive whoosh


    【解决方案1】:

    除了使用 lower() 或 upper(),您可以使用 casefold() 进行字符串比较。

    给出here的一个很好的例子。

    简单来说就是:

    s1 = 'Apple'
    s3 = 'aPPle'
    s1.casefold() == s3.casefold()
    

    返回 True。

    【讨论】:

      【解决方案2】:

      我知道这是一个较老的问题,但如果像我这样的人来这里寻找解决方案,我想会回复。

      定义架构时需要使用 CaseSensitivizer 类。这就是您将如何使用它从文档中的快速入门示例创建架构

      >>> from whoosh.index import create_in
      >>> from whoosh.fields import *
      >>> from whoosh import analysis
      >>> class CaseSensitivizer(analysis.Filter):
              def __call__(self, tokens):
                  for t in tokens:
                      yield t
                      if t.mode == "index":
                          low = t.text.lower()
                          if low != t.text:
                              t.text = low
                              yield t
      >>> myanalyzer = analysis.RegexTokenizer() | CaseSensitivizer()
      >>> schema = Schema(title=TEXT(stored=True), path=ID(stored=True), content=TEXT(analyzer=myanalyzer))
      

      现在您可以使用此架构来创建索引并执行您之前所做的搜索。这对我有用。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-12-02
        • 1970-01-01
        • 1970-01-01
        • 2010-09-15
        • 2021-02-18
        • 1970-01-01
        • 2021-10-31
        • 1970-01-01
        相关资源
        最近更新 更多