基于多个分隔符拆分字符串,同时保留它们

时间:2017-03-25 01:21:03

标签: python string split whitespace sentence

我正在输入5个句子并需要使用多个分隔符进行拆分(,/!/?)

不幸的是,在编写代码时,我只考虑字母并放置这些分隔符并使用.split()。它工作得很好。

这是代码:

final_text = ''
split_one = ''
input_text = input("Enter the data: ")
count_d = input_text.count("!") + input_text.count("?") + input_text.count(".")

if count_d == 5:
            final_text = input_text
            final_text = final_text.replace('!', '! ').replace('?', '? ').replace('.', '. ')
            split_one = final_text.split()
            i = 0
            while True:
                print(split_one[i])
                i += 1
                if i == 5:
                    break

输入:a.b?c!d.f!

The output was 
a.
b?
c!
d.
f!

但我实际上是在输入句子而不是字母。 E.g

hi.how are you? I am good! what about you?bye!

它给了我:

 hi.
 how
 are
 you?
 I

而不是

hi.
how are you?
I am good!
what about you?
bye!

我可以做些什么来避免由于空格而导致的分割,并且仅针对分隔符进行分割? (,/。/!)

PS:我不会使用任何外部包。版本是3.6

1 个答案:

答案 0 :(得分:2)

您可以使用itertools.groupby按标点分割字符串,例如:

>>> import itertools as it
>>> s = 'hi.how are you? I am good! what about you?bye!'
>>> r = [''.join(v).strip() for k, v in it.groupby(s, lambda c: c in '.!?')]
>>> r
['hi', '.', 'how are you', '?', 'I am good', '!', 'what about you', '?', 'bye', '!']
>>> for sentence, punct in zip(*[iter(r)]*2):
...     print(sentence + punct)
hi.
how are you?
I am good!
what about you?
bye!

如果您不关心标点符号,则可以使用:

>>> [''.join(v).strip() for k, v in it.groupby(s, lambda c: c in '.!?') if not k]
['hi', 'how are you', 'I am good', 'what about you', 'bye']