2017-03-05 44 views
0
punc_list = [".",";",":","!","?","/","\\",",","#","@","$","&",")","(","'","\""] 
new_s = '' 
for i in s: 
    if i not in punc_list: 
     new_s += i 
return new_s.lower() 

更換標點符號如果輸入如何使用空白

s = ("Hey! M'y nam;e i's") 

我想輸出是:

s = ('hey m y name e i s') 

我無法用空格代替PUNC

+0

這個功課,還是可以使用正則表達式?另外,只是_exactly那些標點符號或_all_特殊字符? –

+0

在'else'分支中,添加一個空白區域。 – DyZ

+0

@tobias_k是的,它是作業。我正在考慮所有特殊字符 – Mar

回答

0

像@DYZ說,你只需要在另一個條件語句用空格代替特殊字符:

def func(s): 
    punc_list = [".",";",":","!","?","/","\\",",","#","@","$","&",")","(","'","\""] 
    new_s = '' 
    for i in s: 
     if i not in punc_list: 
      new_s += i 
     else: 
      new_s += ' ' 
    return new_s.lower() 

s = ("Hey! M'y nam;e i's") 
new_s = func(s) 
print (new_s) 

輸出看起來像你想要的東西:hey m y nam e i s

0

我只需在if i not in punc_list:中添加else語句,以便代碼如下所示:

punc_list = [".",";",":","!","?","/","\\",",","#","@","$","&",")","(","'","\""] 
new_s = '' 
for i in s: 
    if i not in punc_list: 
     new_s += i 
    else: 
     new_s += ' ' 

return new_s.lower() 

這樣做只是說: 如果字符不在標點符號列表將其添加到新string。 如果它位於標點符號列表中,請將空格添加到新的string

1

使用str.translate。將punc_list中的所有字符轉換爲空格。

>>> punc_list = [".",";",":","!","?","/","\\",",","#","@","$","&",")","(","'","\""] 
>>> s = "Hey! M'y nam;e i's" 
>>> s.translate({ord(p): " " for p in punc_list}) 
'Hey M y nam e i s' 

您可以創建使用字典理解的蒼蠅,它映射所有的標點字符代碼字典映射(使用ord功能)的空間。

+1

爲什麼不只是'{ord(x):''爲punc_list中的x}'? –

+0

是更簡單的謝謝 –

0

看到這個代碼,使用2個循環:

punc_list = [".",";",":","!","?","/","\\",",","#","@","$","&",")","(","'","\""] 
s = "Hey! M'y nam;e i's" 
new_s = '' 

for x in punc_list: 
    for i in s: 
    if i==x: 
     s=s.replace(i,new_s) 


print(s) 
2

你忘了添加一個空格' '當字符是標點符號。另外,punc_list實際上不一定是list;您可以將其設爲一個長字符串並迭代字符,或者如註釋中所述,只需使用string.punctuation即可。並提高查找速度,你也可以讓它set,但它確實不應該多大關係在這種情況下:

punc_list = set('.;:!?/\\,#@$&)(\'"') # or use string.punctuation 

def no_punc(s): 
    new_s = '' 
    for i in s: 
     if i not in punc_list: 
      new_s += i 
     else: 
      new_s += ' ' 
    return new_s.lower() 

還是有點短,使用三元表達式... if ... else ...

def no_punc(s): 
    new_s = '' 
    for i in s: 
     new_s += i if i not in punc_list else ' ' 
    return new_s.lower() 

或者更短,使用str.join

def no_punc(s): 
    return ''.join(i if i not in punc_list else ' ' for i in s).lower() 

甚至短,基於R egular expressions re

import re 
def no_punc(s): 
    return re.sub("\W", " ", s).lower() 
1

作業問題是否應該幫助您瞭解循環?學習字典和翻譯也是有用的,我想。

t = str.maketrans(dict.fromkeys(punc_list, " ")) 
new_s = s.lower().translate(t)