我是 Python 新手,我有一个标记化作业
输入是一个包含句子的 .txt 文件
输出是带有令牌的 .txt 文件,当我说令牌时,我的意思是:简单的单词,',','!' ,'?' ,'。' '''
我有这个功能:
输入:
Elemnt 是一个带或不带标点符号的单词,可以是这样的单词:嗨或说:或说“
StrForCheck :是一个标点符号数组,我想将其与单词分开
TokenFile:是我的输出文件
def CheckIfSEmanExist(Elemnt,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')
代码在标点符号数组上循环,如果他找到一个,我检查标点符号是单词中的第一个字母还是最后一个字母,然后在我的输出文件中将单词和标点符号分别写入不同的行
但我的问题是,除了这些词之外,它对整个文本都效果很好:
工作岗位”、创建“、公共”、警察“
注意
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: ]
它在运行时会“吐出”令牌。你可以这样使用它:
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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)