我正在使用 Whoosh 索引和搜索大量文档,我需要搜索的许多内容都带有连字符。 Whoosh 似乎将连字符视为某种特殊字符,但就我的生活而言,我无法弄清楚它的行为。
有人可以建议 Whoosh 在索引和搜索时如何处理连字符吗?
最佳答案
Whoosh 只是将所有标点符号视为空格。假设默认 AND
搜索、查询dual-scale thermometer
相当于dual AND scale AND thermometer
.这将找到包含 dual-scale digital thermometer
的文档, 但它也会找到 dual purpose bathroom scale with thermometer
.
避免这种情况的一种解决方案是将查询中带连字符的词变成短语:"dual-scale" thermometer
,相当于 "dual scale" AND thermometer
.
您还可以强制 Whoosh 接受连字符作为单词的一部分。您可以通过覆盖 RegexTokenizer
来做到这一点StandardAnalyzer
中的表达式使用接受连字符作为 token 有效部分的正则表达式。
from whoosh import fields, analysis
myanalyzer = analysis.StandardAnalyzer(expression=r'[\w-]+(\.?\w+)*')
schema = fields.Schema(myfield=fields.TEXT(analyzer=myanalyzer))
现在搜索 dual-scale thermometer
相当于dual-scale AND thermometer
并会找到 dual-scale digital thermometer
但不是 "dual purpose bathroom scale with thermometer"
.
但是,您将无法单独搜索带连字符的词。如果您的文档包含 high-quality components
,如果您搜索 quality
,则不会匹配它;只有high-quality
,因为这现在已经成为一个 token 。由于这种副作用,除非您的内容严格限制将连字符用于真正原子连字符的单词,否则我建议使用短语方法。
关于python - 使用 Whoosh 搜索和索引带连字符的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36507752/