python中的单词标记化

问题描述

我是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','</s>'],but what i got is:
['<','s','>','<','/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)

解决方法

这看起来像标记。您可以使用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','c']

但是,如果要保留标签,只需执行以下操作:

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

print(corpus)

sample.txt包含您提供的语料库示例。

输出:

['<s>','</s>','<s>','</s>']