在 python nltk.word_tokenize 中保留尾随标点符号
keep trailing punctuation in python nltk.word_tokenize
关于删除标点符号有很多可用的方法,但我似乎找不到任何保留它的方法。
如果我这样做:
from nltk import word_tokenize
test_str = "Some Co Inc. Other Co L.P."
word_tokenize(test_str)
Out[1]: ['Some', 'Co', 'Inc.', 'Other', 'Co', 'L.P', '.']
最后一个“.”被推入它自己的令牌。但是,如果最后还有另一个词,最后一个“。”被保留:
from nltk import word_tokenize
test_str = "Some Co Inc. Other Co L.P. Another Co"
word_tokenize(test_str)
Out[1]: ['Some', 'Co', 'Inc.', 'Other', 'Co', 'L.P.', 'Another', 'Co']
我希望这始终作为第二种情况执行。现在,我正在做:
from nltk import word_tokenize
test_str = "Some Co Inc. Other Co L.P."
word_tokenize(test_str + " |||")
因为我很有信心扔掉“|||”在任何给定时间,但不知道我可能想要保留的其他标点符号可能会被删除。有没有更好的方法来完成这个?
你可以使用 re
吗?
import re
test_str = "Some Co Inc. Other Co L.P."
print re.split('\s', test_str)
这将根据间距拆分输入字符串,同时保留标点符号。
如果一个句子以缩写词结尾,我们只写一个句点,而不是两个,这是拼写的一个怪癖。 nltk 的分词器没有 "remove" 它,而是将其拆分,因为句子结构 ("a sentence must end with a period or other suitable punctuation") 对于 NLP 工具比缩写的一致表示更重要。分词器足够智能,可以识别大多数缩写,因此它不会分隔 L.P.
mid-sentence 中的句点。
您使用 |||
的解决方案导致句子结构不一致,因为您现在没有 sentence-final 标点符号。更好的解决方案是仅在缩写后添加缺失的句点。这是一种方法,丑陋但与分词器自己的缩写识别器一样可靠:
toks = nltk.word_tokenize(test_str + " .")
if len(toks) > 1 and len(toks[-2]) > 1 and toks[-2].endswith("."):
pass # Keep the added period
else:
toks = toks[:-1]
PS。您接受的解决方案将完全改变标记化,留下 all 标点符号附加到相邻的词(以及其他不良影响,如引入空标记)。这很可能不是您想要的。
关于删除标点符号有很多可用的方法,但我似乎找不到任何保留它的方法。
如果我这样做:
from nltk import word_tokenize
test_str = "Some Co Inc. Other Co L.P."
word_tokenize(test_str)
Out[1]: ['Some', 'Co', 'Inc.', 'Other', 'Co', 'L.P', '.']
最后一个“.”被推入它自己的令牌。但是,如果最后还有另一个词,最后一个“。”被保留:
from nltk import word_tokenize
test_str = "Some Co Inc. Other Co L.P. Another Co"
word_tokenize(test_str)
Out[1]: ['Some', 'Co', 'Inc.', 'Other', 'Co', 'L.P.', 'Another', 'Co']
我希望这始终作为第二种情况执行。现在,我正在做:
from nltk import word_tokenize
test_str = "Some Co Inc. Other Co L.P."
word_tokenize(test_str + " |||")
因为我很有信心扔掉“|||”在任何给定时间,但不知道我可能想要保留的其他标点符号可能会被删除。有没有更好的方法来完成这个?
你可以使用 re
吗?
import re
test_str = "Some Co Inc. Other Co L.P."
print re.split('\s', test_str)
这将根据间距拆分输入字符串,同时保留标点符号。
如果一个句子以缩写词结尾,我们只写一个句点,而不是两个,这是拼写的一个怪癖。 nltk 的分词器没有 "remove" 它,而是将其拆分,因为句子结构 ("a sentence must end with a period or other suitable punctuation") 对于 NLP 工具比缩写的一致表示更重要。分词器足够智能,可以识别大多数缩写,因此它不会分隔 L.P.
mid-sentence 中的句点。
您使用 |||
的解决方案导致句子结构不一致,因为您现在没有 sentence-final 标点符号。更好的解决方案是仅在缩写后添加缺失的句点。这是一种方法,丑陋但与分词器自己的缩写识别器一样可靠:
toks = nltk.word_tokenize(test_str + " .")
if len(toks) > 1 and len(toks[-2]) > 1 and toks[-2].endswith("."):
pass # Keep the added period
else:
toks = toks[:-1]
PS。您接受的解决方案将完全改变标记化,留下 all 标点符号附加到相邻的词(以及其他不良影响,如引入空标记)。这很可能不是您想要的。