[英]Split more than one word in python
如何用python編寫一個可以拆分多個單詞或字符的程序? 例如,我有這些句子: Hi, This is a test. Are you surprised?
Hi, This is a test. Are you surprised?
在此示例中,我需要我的程序將這些句子分隔為',','!','?' 和'。'。 我知道str
庫和NLTK
split,但我需要知道是否有任何內部pythonic方式(例如split)?
使用re.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'']
您正在尋找NLTK軟件包的tokenize
功能。 NLTK
代表自然語言工具包
或嘗試從re
模塊re
re.split
。
從re doc。
>>> 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
方法對文本進行逐字分割.
。
def get_words(s):
l = []
w = ''
for c in s:
if c in '-!?,. ':
if w != '':
l.append(w)
w = ''
else:
w = w + c
if w != '':
l.append(w)
return l
>>> s = "Hi, This is a test. Are you surprised?"
>>> print get_words(s)
['Hi', 'This', 'is', 'a', 'test', 'Are', 'you', 'surprised']
If you change '-!?,. ' into '-!?,.'
The output will be:
['Hi', ' This is a test', ' Are you surprised']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.