1

I am attempting to build a TokenStream from a Python Sequence. Just for fun I want to be able to pass my own Tokens directly to

pylucene.Field("MyField", MyTokenStream)

I tried to make "MyTokenStream" by...

terms = ['pant', 'on', 'ground', 'look', 'like', 'fool']
stream = pylucene.PythonTokenStream()
for t in terms:
  stream.addAttribute(pylucene.TermAttribute(t))

But unfortunately a wrapper for "TermAttribute" doesn't exist, or for that matter any of the other Attribute classes in lucene so I get a NotImplemented error when calling them.

This doesn't raise an exception - but I'm not not sure if it's even setting the terms.

PythonTokenStream(terms)
4

1 回答 1

3

Python* 类旨在通过子类化来自定义行为。在 TokenStream 的情况下,incrementToken 方法需要被覆盖。

class MyTokenStream(lucene.PythonTokenStream):
    def __init__(self, terms):
        lucene.PythonTokenStream.__init__(self)
        self.terms = iter(terms)
        self.addAttribute(lucene.TermAttribute.class_)
    def incrementToken(self):
        for term in self.terms:
            self.getAttribute(lucene.TermAttribute.class_).setTermBuffer(term)
            return True
        return False

mts = MyTokenStream(['pant', 'on', 'ground', 'look', 'like', 'fool'])
while mts.incrementToken():
    print mts

<MyTokenStream: (pant)>
<MyTokenStream: (on)>
<MyTokenStream: (ground)>
<MyTokenStream: (look)>
<MyTokenStream: (like)>
<MyTokenStream: (fool)>

也可以存储 addAttribute 的结果,无需 getAttribute。我的lupyne项目有一个例子

于 2011-11-28T17:51:15.890 回答