MarkF6
MarkF6

Reputation: 503

Python: open treetagger in script

How can I use the treetagger in a python-script?

I have a sentence given, and the treetagger should analyze it. In a normal command line, I can do the following:

echo 'This is a test!' | cmd/tree-tagger-english-utf8  

but how can I do this in a python script?

The output of the command above is the following:

echo 'This is a test!' | cmd/tree-tagger-english
    reading parameters ...
    tagging ...
     finished.
This    DT  this
is  VBZ be
a   DT  a
test    NN  test
!   SENT    !

In my script, I need the tags, i.e. "DT", "VBZ", "DT", "NN", "SENT" which I'd like to save in a list. I need these tags later to insert them in a string.

Thanks for any help! :)

Upvotes: 2

Views: 1526

Answers (2)

hugom
hugom

Reputation: 1305

You can also use miotto's treetagger-python module, which provides a very easy-to-use interface to the TreeTagger.

Just be sure to define a new TREETAGGER environment variable so that the Python module knows where to find the TreeTagger executables. The rest looks pretty much like this:

>>> from treetagger import TreeTagger
>>> tt_en = TreeTagger(encoding='utf-8', language='english')
>>> from pprint import pprint
>>> pprint(tt_en.tag('Does this thing even work?'))
[[u'Does', u'VBZ', u'do'],
 [u'this', u'DT', u'this'],
 [u'thing', u'NN', u'thing'],
 [u'even', u'RB', u'even'],
 [u'work', u'VB', u'work'],
 [u'?', u'SENT', u'?']]

Here is a blog post I made detailing installation and testing, if you need further insructions.

Upvotes: 1

Marcel
Marcel

Reputation: 1286

Look at the subprocess module: a simple example follows...

$ cat test.py 
#!/usr/bin/python
import os
import sys
import subprocess

list_of_lists = []

process = subprocess.Popen(["cmd/tree-tagger-english-utf8"], stdout=subprocess.PIPE)
(output, err) = process.communicate(sys.stdin)
count = 0
for line in output.split('\n'):
    # condition to skip the first 3 lines
    if count<3:
        count=count+1
    else:
        new_list = [elem for elem in line.split()]
        list_of_lists.append(new_list)
exit_code = process.wait()
print list_of_lists
$ 

Upvotes: 1

Related Questions