lei*_*rem 7 python string split
我正在尝试将字符串分成单词,删除空格和标点符号.
我尝试使用该split()方法,立即传递所有标点符号,但我的结果不正确:
>>> test='hello,how are you?I am fine,thank you. And you?'
>>> test.split(' ,.?')
['hello,how are you?I am fine,thank you. And you?']
Run Code Online (Sandbox Code Playgroud)
我实际上已经知道如何用正则表达式做这个,但我想弄清楚如何使用它split().请不要给我一个正则表达式的解决方案.
lar*_*sks 14
如果你想根据多个分隔符拆分一个字符串,就像在你的例子中一样,re尽管存在奇怪的异议,你仍然需要使用该模块,如下所示:
>>> re.split('[?.,]', test)
['hello', 'how are you', 'I am fine', 'thank you', ' And you', '']
Run Code Online (Sandbox Code Playgroud)
这是可能的使用得到了类似的结果split,但你需要为每一个字符调用一次分裂,你需要遍历以前的拆分结果.这有效,但很难看:
>>> sum([z.split()
... for z in sum([y.split('?')
... for y in sum([x.split('.')
... for x in test.split(',')],[])], [])], [])
['hello', 'how', 'are', 'you', 'I', 'am', 'fine', 'thank', 'you', 'And', 'you']
Run Code Online (Sandbox Code Playgroud)
这用于sum()展平上一次迭代返回的列表.
Eli*_*ria 12
这是我在不使用re模块的情况下可以想到的最佳方式:
"".join((char if char.isalpha() else " ") for char in test).split()
Run Code Online (Sandbox Code Playgroud)
由于您不想使用re模块,因此可以使用:
test.replace(',',' ').replace('.',' ').replace('?',' ').split()
Run Code Online (Sandbox Code Playgroud)
您可以编写一个函数来扩展使用.split():
def multi_split(s, seprators):
buf = [s]
for sep in seprators:
for loop, text in enumerate(buf):
buf[loop:loop+1] = [i for i in text.split(sep) if i]
return buf
Run Code Online (Sandbox Code Playgroud)
并尝试:
>>> multi_split('hello,how are you?I am fine,thank you. And you?', ' ,.?')
['hello', 'how', 'are', 'you', 'I', 'am', 'fine', 'thank', 'you', 'And', 'you']
这样会更清楚,可以在其他情况下使用。
larsks答案的修改版本,您无需自己输入所有标点符号:
import re, string
re.split("[" + string.punctuation + "]+", test)
['hello', 'how are you', 'I am fine', 'thank you', ' And you', '']
Run Code Online (Sandbox Code Playgroud)