【问题标题】:Python: open treetagger in scriptPython:在脚本中打开treetagger
【发布时间】:2015-10-16 07:46:19
【问题描述】:

如何在 python 脚本中使用treetagger

我有一个句子,treetagger 应该分析它。在normal 命令行中,我可以执行以下操作:

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

但是如何在 python 脚本中做到这一点?

上述命令的输出如下:

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    !

在我的脚本中,我需要我想保存在列表中的标签,即“DT”、“VBZ”、“DT”、“NN”、“SENT”。稍后我需要这些标签将它们插入到字符串中。

感谢您的帮助! :)

【问题讨论】:

    标签: python pos-tagger


    【解决方案1】:

    查看subprocess 模块:下面是一个简单的示例...

    $ 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
    $ 
    

    【讨论】:

    • 您忘记了输入。 process.communicate('This is a test')
    • 我有一个问题:“/usr/bin/xargs”是什么意思?输入进程行后,我无法输入任何其他行(似乎python崩溃了......)
    • xargs 命令只是一个示例。 “输入任何其他行”是什么意思???
    • 我已经编辑了我的答案以考虑您的问题的上下文,尝试使用您的树标记器看看它是否按您的意愿运行;)
    • 嗯...在输入进程行后,我得到: >>> process = subprocess.Popen(["cmd/tree-tagger-english"], stdout=subprocess.PIPE) > >> 读取参数...标记... ...是否可以直接在脚本中获取输出?我想将 treetagger 的输出保存在列表中...
    【解决方案2】:

    您也可以使用miotto's treetagger-python module,它为TreeTagger 提供了一个非常易于使用的界面。

    请务必定义一个新的 TREETAGGER 环境变量,以便 Python 模块知道在哪里可以找到 TreeTagger 可执行文件。其余的看起来很像这样:

    >>> 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,如果您需要进一步的指导。

    【讨论】: