Poe*_*dit 2 python text-processing tokenize
我有一个像这样的字符串:
sentence = 'This is   a  nice    day'
我想要以下输出:
output = ['This is', 'a  nice',  'day']
在这种情况下,我将字符串分割为n= 3或更多的空格,这就是为什么像上面显示的那样分割字符串。
我怎样才能有效地做到这一点n?
您可以尝试使用Python的正则表达式拆分:
sentence = 'This is   a  nice day'
output = re.split(r'\s{3,}', sentence)
print(output)
['This is', 'a  nice day']
为了处理实际变量n,我们可以尝试:
n = 3
pattern = r'\s{' + str(n) + ',}'
output = re.split(pattern, sentence)
print(output)
['This is', 'a  nice day']