我要输入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!
但是我实际上是在输入句子而不是字母。例如
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
最佳答案
您可以使用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']
关于python - 根据多个定界符分割字符串,同时保留它们,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43011492/