Ok I want to split this sentence completely, Using that big space gap.
with open("Sample2.txt","r") as f:
for line in f:
B.append(line.split(" "))
print (B)
我这样得到 OUTPUT :
[['Ok I want to split', '', '', 'this sentence completely, Using that big space gap.\n']]
逻辑上这是对的。但是我不希望在分割之间有两个额外的条目。
IDEAL OUTPUT 应为:
[['Ok I want to split','this sentence completely, Using In that big space gap.\n']]
编辑:假设分割之间有任意数量的空格,并且无法手动对其进行计数。
哦,我该怎么做才能解决这个令人烦恼的问题。\ n' \ n' ??
答案 0 :(得分:1)
您需要使用正则表达式:
>>> re.split(r' {4,}', s)
['Ok I want to split', 'this sentence completely. Using that big space gap.']
该版本将拆分为" 4个或更多空格"。
如果您想放弃\n
,请使用foo.rstrip()
,其中foo
是您的字符串。
答案 1 :(得分:1)
使用regexp +
(空格后跟1 +空格),并删除输入字符串以摆脱\n
。
import re
re.split(r' +', a.strip())
答案 2 :(得分:0)
在点旁边存在多个空格或空格上的分割。
re.split(r'\s{2,}|(?<=\.)\s+', strin)
示例:的
>>> h = 'Ok I want to split this sentence completely. Using that big space gap.'
>>> re.split(r'\s{2,}|(?<=\.)\s+', h)
['Ok I want to split', 'this sentence completely.', 'Using that big space gap.']
>>>