2011-11-30 150 views
2

我是python中的新成員,我遇到了一些問題。如何從python中的字符串中刪除小寫字詞

我有一個數組(或它在Python的說列表)是這樣的:

list = [ 'NICE dog' , 'blue FLOWER' , 'GOOD cat' , 'YELLOW caw'] 

正如你看到的這個數組的每個元素都包含了一些話。這些詞都是小寫和大寫。

如何從這個數組中刪除每個小寫字母?

比如我想有作爲的結果這份名單:

list = [ 'NICE' , 'FLOWER' , 'GOOD' , 'YELLOW'] 
+1

不覆蓋內置'list'! – moooeeeep

+3

你需要考慮混合大小寫的單詞嗎?例如,'NICE小狗'。這些應該如何處理? –

+0

如果字符串是「尼斯小狗」,我只想回顧'尼斯' – gaggina

回答

9
l = [ 'NICE dog' , 'blue FLOWER' , 'GOOD cat' , 'YELLOW caw'] 

output = [' '.join(w for w in a.split() if w.isupper()) for a in l] 
# or:  
output = [' '.join(filter(str.isupper, a.split())) for a in l] 

回報:(不要使用list變量名)

['NICE', 'FLOWER', 'GOOD', 'YELLOW'] 

+0

謝謝你它工作很好:) – gaggina

3

以下將做到這一點:

def remove_lower(s): 
    return ' '.join(w for w in s.split(' ') if not w.islower()) 

l = [ 'NICE dog' , 'blue FLOWER' , 'GOOD cat' , 'YELLOW caw'] 

l = map(remove_lower, l) 
1

這裏是一種與re(正則表達式)模塊,以做到這一點:

list = map(lambda l: re.sub(r'\b\w*[a-z]+\w*\b','',l).strip(), list) 
0
list = [ 'NICE dog' , 'blue FLOWER' , 'GOOD cat' , 'YELLOW caw'] 

print [word for pair in list for word in pair.split() if not word.islower()] 
0
lst = [ 'NICE dog' , 'blue FLOWER' , 'GOOD cat' , 'YELLOW caw'] 

for i in range(len(lst)): 
    tmp = "" 
    for j in range(len(lst[i])): 
     if ord(lst[i][j]) <= ord('Z'): 
      tmp = tmp + lst[i][j] 
    lst[i] = tmp.strip() 
print(lst) #['NICE', 'FLOWER', 'GOOD', 'YELLOW'] 
2

string.translate()將迅速刪除指定的字符:

>>> import string 
>>> mylist=['NICE dog', 'blue FLOWER', 'GOOD cat', 'YELLOW caw'] 
>>> print [s.translate(None, string.ascii_lowercase) for s in mylist] 
['NICE', 'FLOWER', 'GOOD', 'YELLOW']