【问题标题】:word tokenization in pythonpython中的单词标记化
【发布时间】:2020-09-12 07:38:42
【问题描述】:

我是 Python 和文本分析的新手,我想标记我的文本语料库:

<s> c a b c b c </s>
<s> a c b a </s>
<s> c a c a c </s>

I wanted to tokenize them into ['<s>','c','a','b','c','</s>'], but what i got is:
['<', 's', '>', 'c', 'a', 'b', 'c', 'b', 'c', '<', '/s', '>']

“s”和“/s”用 分隔,作为不同的标记。有没有办法解决这个问题?

代码如下:

import nltk
#read file
f = open('Text Corpus.txt','r')
corpus = f.read()
print (corpus)

#tokenize
tokens = nltk.word_tokenize(corpus)
print(tokens)

【问题讨论】:

  • 您应该打开文件“rt” - 对于您想要的,只需f.split() 就可以了。

标签: python text nltk tokenize


【解决方案1】:

这看起来像标记。您可以使用BeautifulSoup 将其删除。

import nltk

from bs4 import BeautifulSoup

corpus = """
<s> c a b c b c </s>
<s> a c b a </s>
<s> c a c a c </s>
"""

print(nltk.word_tokenize(BeautifulSoup(corpus, "html.parser").get_text()))

输出:

['c', 'a', 'b', 'c', 'b', 'c', 'a', 'c', 'b', 'a', 'c', 'a', 'c', 'a', 'c']

但是,如果您想保留标签,只需这样做:

with open("sample.txt") as f:
    corpus = f.read().split()

print(corpus)

sample.txt 持有你给出的语料库示例。

输出:

['<s>', 'c', 'a', 'b', 'c', 'b', 'c', '</s>', '<s>', 'a', 'c', 'b', 'a', '</s>', '<s>', 'c', 'a', 'c', 'a', 'c', '</s>']

【讨论】:

    猜你喜欢
    • 2016-12-19
    • 1970-01-01
    • 2019-06-22
    • 2011-01-22
    • 2014-02-17
    • 1970-01-01
    • 2019-06-13
    • 2020-11-03
    • 1970-01-01
    相关资源
    最近更新 更多