简体   繁体   English

如何从python中删除字符串中的小写单词

[英]how to delete lowercase words from a string in python

I'm new in python and I'm having some issues doing a simple thing. 我是python的新手,我有一些问题在做一件简单的事情。

I've an array (or list as it's said in python) like this: 我有一个数组(或在python中说的列表),如下所示:

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

As you see each element of this array contains some words. 如您所见,此数组的每个元素都包含一些单词。 These words is both lowercase and uppercase. 这些单词都是小写和大写。

How I can delete from this array each lowercase words? 我怎样才能从这个数组中删除每个小写的单词?

For example I'd like to have as result this list: 例如,我想将此列表作为结果:

list = [ 'NICE' , 'FLOWER' , 'GOOD' , 'YELLOW']
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]

returns: 收益:

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

(Don't use list as variable name.) (不要将list用作变量名。)

The following will do it: 以下将这样做:

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)

string.translate() will quickly delete specified characters: 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']

这是使用re (正则表达式)模块执行此操作的方法:

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

print [word for pair in list for word in pair.split() if not word.islower()]
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']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM