比如我想:你可以在一条线上调用多种方法吗?
texta = text.lower()
textacopy1 = texta.replace(string.punctuation, ' ')
textacopy2 = textacopy1.split(' ')
是否有这样做,而不必分配多个变量的更清洁的方式?
如果2.7和3.x之间有区别,我更喜欢3.x解释。
比如我想:你可以在一条线上调用多种方法吗?
texta = text.lower()
textacopy1 = texta.replace(string.punctuation, ' ')
textacopy2 = textacopy1.split(' ')
是否有这样做,而不必分配多个变量的更清洁的方式?
如果2.7和3.x之间有区别,我更喜欢3.x解释。
你可以用一个变量,你不要做不必使用可能导致混淆的多个变量。另外代码将会更干净。你也可以在一行中完成。
text = text.lower()
text = text.replace(string.punctuation, ' ')
text = text.split(' ')
你也可以做到在同一行
text = text.lower().replace(string.punctuation, ' ').split(' ')
使用正则表达式,它作为我可以告诉大家,'代替(字符串是更清洁
In [132]: split_str = re.compile(r'[{} ]+'.format(string.punctuation))
In [133]: split_str.split("You can do it with one variable you don't have to use multiple variable which can cause confusion. Also code will be much cleaner. You can do it in one line also.")
Out[133]:
['You',
'can',
'do',
'it',
.....
'in',
'one',split_string =
'line',
'also',
'']
顺便说一句,就.punctuation,'')'可能不会做你想做的。您必须将其称为“标点符号”中包含的所有单个字符。 – mkrieger1 2015-03-03 09:48:53
@ mkrieger1是的,那是我用循环修复的一个问题。 – Omicron 2015-03-04 08:40:08