2014-11-21 45 views
1

我有一個列表,如下圖所示:Python的剝離從列表中的基於項的字符串的字符串

exclude = ["please", "hi", "team"] 

我有一個字符串,如下所示:

text = "Hi team, please help me out." 

我想我的字符串看作:

text = ", help me out." 

有效地剝離出可能出現在列表中的任何字exclude

我嘗試以下:

if any(e in text.lower()) for e in exclude: 
     print text.lower().strip(e) 

但上面if語句返回一個布爾值,因此我得到下面的錯誤:

NameError: name 'e' is not defined 

我如何得到這個工作?

+0

爲什麼逗號消失? – mgilson 2014-11-21 08:35:31

+0

...和點? – ngulam 2014-11-21 08:46:46

+0

這是我匆匆打字。標點可以在那裏或不在那裏。對我的輸出無關緊要。爲了避免混淆,我會解決這個問題。 – user1452759 2014-11-24 04:46:12

回答

3

像這樣的事情?

>>> from string import punctuation 
>>> ' '.join(x for x in (word.strip(punctuation) for word in text.split()) 
                if x.lower() not in exclude) 
'help me out 

如果你想保留尾隨/領先標點與不存在於exclude的話:

>>> ' '.join(word for word in text.split() 
          if word.strip(punctuation).lower() not in exclude) 
'help me out.' 

第一個是等價於:

>>> out = [] 
>>> for word in text.split(): 
     word = word.strip(punctuation) 
     if word.lower() not in exclude: 
      out.append(word) 
>>> ' '.join(out) 
'help me out' 
+0

這是優秀的!謝謝! – user1452759 2014-11-24 07:10:26

0

,如果你不擔心標點符號:

>>> import re 
>>> text = "Hi team, please help me out." 
>>> text = re.findall("\w+",text) 
>>> text 
['Hi', 'team', 'please', 'help', 'me', 'out'] 
>>> " ".join(x for x in text if x.lower() not in exclude) 
'help me out' 

在上面的代碼,re.findall會發現所有的話,並把它們在列表中。
\w比賽A-Za-z0-9
+指一個或多個發生

+0

PLZ提供downvote的任何理由。所以我可以糾正它。 – Hackaholic 2014-11-21 08:48:09

+0

我不知道爲什麼有人低估了,但其中一個原因可能是這會把'can't'這樣的單詞分成兩個單獨的單詞'can t'。 – 2014-11-21 08:55:55

+0

是的,但在注意我給了,如果OP不關心punchuatation – Hackaholic 2014-11-21 08:58:19

1

您可以使用使用這個(請記住它區分大小寫)

for word in exclude: 
    text = text.replace(word, "") 
0

這將用空格替換非字母數字或屬於停用詞列表的所有內容,然後將結果拆分爲要保留的單詞。最後,這個列表被連接成一個字符串,在這個字符串中間隔字。注意:區分大小寫。

' '.join (re.sub('\W|'+'|'.join(stopwords),' ',sentence).split()) 

用法示例:

>>> import re 
>>> stopwords=['please','hi','team'] 
>>> sentence='hi team, please help me out.' 
>>> ' '.join (re.sub('\W|'+'|'.join(stopwords),' ',sentence).split()) 
'help me out' 
0

使用簡單的方法:

import re 
exclude = ["please", "hi", "team"] 
text = "Hi team, please help me out." 
l=[] 

te = re.findall("[\w]*",text) 
for a in te: 
    b=''.join(a) 
    if (b.upper() not in (name.upper() for name in exclude)and a): 
     l.append(b) 
print " ".join(l) 

希望它可以幫助