Python 代币化

Python Tokenization

我是 Python 的新手,我有一个标记化任务 输入是一个包含句子的 .txt 文件 输出是带有令牌的 .txt 文件,当我说令牌时,我的意思是:简单的词,',','!' , '?' , '.' ' " '

我有这个功能: 输入: Elemnt 是一个带或不带标点符号的词,可以是这样的词: Hi 或 said: 或 said" StrForCheck :是一组标点符号,我想将其与单词分开 TokenFile:是我的输出文件

def CheckIfSEmanExist(元素、StrForCheck、TokenFile):

FirstOrLastIsSeman = 0

for seman in StrForCheck:
    WordSplitOnSeman = Elemnt.split(seman)
    if len(WordSplitOnSeman) > 1:
        if Elemnt[len(Elemnt)-1] == seman:
            FirstOrLastIsSeman = len(Elemnt)-1
        elif Elemnt[0] == seman:
            FirstOrLastIsSeman = 1

if FirstOrLastIsSeman == 1:
    TokenFile.write(Elemnt[0])
    TokenFile.write('\n')
    TokenFile.write(Elemnt[1:-1])
    TokenFile.write('\n')

elif FirstOrLastIsSeman == len(Elemnt)-1:
    TokenFile.write(Elemnt[0:-1])
    TokenFile.write('\n')
    TokenFile.write(Elemnt[len(Elemnt)-1])
    TokenFile.write('\n')

elif FirstOrLastIsSeman == 0:
    TokenFile.write(Elemnt)
    TokenFile.write('\n')

代码遍历标点符号数组,如果他找到一个,我检查标点符号是单词中的第一个字母还是最后一个字母,然后在我的输出文件中将单词和标点符号分别写入一个不同的行

但我的问题是它在整个文本上效果很好,除了那些词: 工作”,创建“,public”,警察

注意

for l in open('some_file.txt', 'r'):
    ...

迭代每一行,所以你只需要考虑在一行中做什么。

考虑以下函数:

def tokenizer(l):
    prev_i = 0
    for (i, c) in enumerate(l):
        if c in ',.?!- ':
            if prev_i != i:
                yield l[prev_i: i]
            yield c
            prev_i = i + 1
    if prev_i != 0:
        yield l[prev_i: ]

它 "spits out" 随着它的发展而标记。你可以这样使用它:

l = "hello, hello, what's all this shouting? We'll have no trouble here"
for tok in tokenizer(l):
    print tok

hello
,

hello
,

what's

all

this

shouting
?

We'll

have

no

trouble

here