如何在字符串而不是列表中输出 NLTK pos_tag?

How to output NLTK pos_tag in the string instead of a list?

我需要在大型数据集上 运行 nltk.pos_tag 并且需要它的输出类似于 Stanford tagger 提供的输出。

例如,当 运行我有以下代码时;

import nltk
text=nltk.word_tokenize("We are going out.Just you and me.")
print nltk.pos_tag(text)

输出是: [('We', 'PRP'), ('are', 'VBP'), ('going', 'VBG'), ('out.Just', 'IN'), ('you', 'PRP'), ('and', 'CC'), ('me', 'PRP'), ( '.', '.')]

在我需要它的情况下:

 We/PRP are/VBP going/VBG out.Just/NN you/PRP and/CC me/PRP ./.

我宁愿不使用字符串函数,而是需要直接输出,因为文本的数量如此之多,它给处理增加了很多时间复杂性

简而言之:

' '.join([word + '/' + pos for word, pos in tagged_sent]

长:

我认为您对使用字符串函数来连接字符串想得太多了,它确实没有那么昂贵。

import time
from nltk.corpus import brown

tagged_corpus = brown.tagged_sents()

start = time.time()

with open('output.txt', 'w') as fout:
    for i, sent in enumerate(tagged_corpus):
        print(' '.join([word + '/' + pos for word, pos in sent]), end='\n', file=fout)

end = time.time() - start
print (i, end)

棕色语料库中的所有 57339 个句子在我的笔记本电脑上花费了 2.955 秒。

[输出]:

$ head -n1 output.txt 
The/AT Fulton/NP-TL County/NN-TL Grand/JJ-TL Jury/NN-TL said/VBD Friday/NR an/AT investigation/NN of/IN Atlanta's/NP$ recent/JJ primary/NN election/NN produced/VBD ``/`` no/AT evidence/NN ''/'' that/CS any/DTI irregularities/NNS took/VBD place/NN ./.

但是使用字符串连接单词和 POS 可能会在以后需要读取标记输出时造成麻烦,例如

>>> from nltk import pos_tag
>>> tagged_sent = pos_tag('cat / dog'.split())
>>> tagged_sent_str = ' '.join([word + '/' + pos for word, pos in tagged_sent])
>>> tagged_sent_str
'cat/NN //CD dog/NN'
>>> [tuple(wordpos.split('/')) for wordpos in tagged_sent_str.split()]
[('cat', 'NN'), ('', '', 'CD'), ('dog', 'NN')]

如果你想保存标记的输出然后再阅读,最好使用pickle来保存tagged_output,例如

>>> import pickle
>>> tagged_sent = pos_tag('cat / dog'.split())
>>> with open('tagged_sent.pkl', 'wb') as fout:
...     pickle.dump(tagged_sent, fout)
... 
>>> tagged_sent = None
>>> tagged_sent
>>> with open('tagged_sent.pkl', 'rb') as fin:
...     tagged_sent = pickle.load(fin)
... 
>>> tagged_sent
[('cat', 'NN'), ('/', 'CD'), ('dog', 'NN')]