在python中拆分多个单词

2024-09-24 02:25:54 发布

您现在位置:Python中文网/ 问答频道 /正文

如何用python编写一个可以拆分多个单词或字符的程序? 例如,我有这些句子:Hi, This is a test. Are you surprised?在这个例子中,我需要我的程序用',','!'来拆分这些句子,'?' 还有“.”。我知道在str库和NLTK中使用split,但我需要知道有没有像split这样的内部pythonic方法?你知道吗


Tags: test程序youishithis字符单词
3条回答

您正在寻找NLTK包的tokenize函数。NLTK代表自然语言工具包

或者从re模块中尝试re.split。你知道吗

来自re文件。你知道吗

>>> re.split('\W+', 'Words, words, words.')
['Words', 'words', 'words', '']
>>> re.split('(\W+)', 'Words, words, words.')
['Words', ', ', 'words', ', ', 'words', '.', '']
>>> re.split('\W+', 'Words, words, words.', 1)
['Words', 'words, words.']
>>> re.split('[a-f]+', '0a3B9', flags=re.IGNORECASE)
['0', '3', '9']

我想我找到了解决问题的巧妙方法。我不需要使用任何模块。我可以使用str库的replace方法,用.替换像!?这样的词。然后我可以使用split方法将文本按.拆分。你知道吗

使用重新拆分地址:

string = 'Hi, This is a test. Are you surprised?'
words = re.split('[,!?.]', string)
print(words)
[u'Hi', u' This is a test', u' Are you surprised', u'']

相关问题 更多 >