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