簡體   English   中英

在python中拆分多個單詞

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM