我在Python中使用NLTK的tokenizer .
已经在论坛上删除了标点符号的大量答案.但是,它们都没有一起解决所有以下问题:
'*u*', '''','""'
有一种解决这两个问题的优雅方式吗?
alv*_*vas 12
解决方案1:标记并删除标记的标点符号
>>> from nltk import word_tokenize
>>> import string
>>> punctuations = list(string.punctuation)
>>> punctuations
['!', '"', '#', '$', '%', '&', "'", '(', ')', '*', '+', ',', '-', '.', '/', ':', ';', '<', '=', '>', '?', '@', '[', '\\', ']', '^', '_', '`', '{', '|', '}', '~']
>>> punctuations.append("''")
>>> sent = '''He said,"that's it."'''
>>> word_tokenize(sent)
['He', 'said', ',', "''", 'that', "'s", 'it', '.', "''"]
>>> [i for i in word_tokenize(sent) if i not in punctuations]
['He', 'said', 'that', "'s", 'it']
>>> [i.strip("".join(punctuations)) for i in word_tokenize(sent) if i not in punctuations]
['He', 'said', 'that', 's', 'it']
Run Code Online (Sandbox Code Playgroud)
解决方案2:删除标点符号然后标记化
>>> import string
>>> string.punctuation
'!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
>>> sent = '''He said,"that's it."'''
>>> " ".join("".join([" " if ch in string.punctuation else ch for ch in sent]).split())
'He said that s it'
>>> " ".join("".join([" " if ch in string.punctuation else ch for ch in sent]).split()).split()
['He', 'said', 'that', 's', 'it']
Run Code Online (Sandbox Code Playgroud)
如果你想一次性对你的字符串进行标记,我认为你唯一的选择就是使用它nltk.tokenize.RegexpTokenizer
.以下方法允许您在删除标点符号之前使用标点符号作为标记来删除字母表中的字符(如第三个要求中所述).换句话说,这种方法将*u*
在剥离所有标点符号之前删除.
那么,解决这个问题的一种方法就是将间隙标记为:
>>> from nltk.tokenize import RegexpTokenizer
>>> s = '''He said,"that's it." *u* Hello, World.'''
>>> toker = RegexpTokenizer(r'((?<=[^\w\s])\w(?=[^\w\s])|(\W))+', gaps=True)
>>> toker.tokenize(s)
['He', 'said', 'that', 's', 'it', 'Hello', 'World'] # omits *u* per your third requirement
Run Code Online (Sandbox Code Playgroud)
这应符合您在上面指定的所有三个标准.但请注意,此标记生成器不会返回令牌等"A"
.此外,我只对以标点符号开头和结尾的单个字母进行标记.否则,"去吧." 不会返回令牌.您可能需要以其他方式细化正则表达式,具体取决于您的数据是什么以及您的期望是什么.
归档时间: |
|
查看次数: |
21939 次 |
最近记录: |