2015-03-02 67 views
1

比如我想:你可以在一条线上调用多种方法吗?

texta = text.lower() 
textacopy1 = texta.replace(string.punctuation, ' ') 
textacopy2 = textacopy1.split(' ') 

是否有这样做,而不必分配多个变量的更清洁的方式?

如果2.7和3.x之间有区别,我更喜欢3.x解释。

+1

顺便说一句,就.punctuation,'')'可能不会做你想做的。您必须将其称为“标点符号”中包含的所有单个字符。 – mkrieger1 2015-03-03 09:48:53

+0

@ mkrieger1是的,那是我用循环修复的一个问题。 – Omicron 2015-03-04 08:40:08

回答

6
result = text.lower().replace(string.punctuation, ' ').split(' ') 

巨大的Python带来了巨大的责任:不要滥用此功能!

PEP 8成文的规范行的最大长度为80个字符, 和分裂的方法链中一个圆点开始新行的正规途径:

result = text.lower().replace(string.punctuation, ' ') 
     .split(' ') 
+0

点点的不错 - 不知道 – volcano 2015-03-02 13:06:44

1

你可以用一个变量,你不要做不必使用可能导致混淆的多个变量。另外代码将会更干净。你也可以在一行中完成。

text = text.lower() 
text = text.replace(string.punctuation, ' ') 
text = text.split(' ') 

你也可以做到在同一行

text = text.lower().replace(string.punctuation, ' ').split(' ') 
1

使用正则表达式,它作为我可以告诉大家,'代替(字符串是更清洁

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', 
    ''] 
相关问题