简体   繁体   中英

Python how to delete lowercase words from a string that is in a list

My question is: how do I delete all the lowercase words from a string that is an element in a list? For example, if I have this list: s = ["Johnny and Annie.", "She and I."]

what do I have to write to make python return newlist = ["Johnny Annie", "She I"]

I've tried this, but it sadly doesn't work:

def test(something):
    newlist = re.split("[.]", something)
    newlist = newlist.translate(None, string.ascii_lowercase)
    for e in newlist:
        e = e.translate(None, string.ascii_lowercase)

Iterate over the elements of the list and eliminate the words in lowercase.

s = s = ["Johnny and Annie.", "She and I."]
for i in s:
    no_lowercase = ' '.join([word for word in i.split(' ') if not word.islower()])
    print(no_lowercase)
>>> s = ["Johnny and Annie.", "She and I."]

You can check if the word is lowercase using islower() and using split to iterate word by word.

>>> [' '.join(word for word in i.split() if not word.islower()) for i in s]
['Johnny Annie.', 'She I.']

To remove punctuation as well

>>> import string
>>> [' '.join(word.strip(string.punctuation) for word in i.split() if not word.islower()) for i in s]
['Johnny Annie', 'She I']

Translate is not the right tool here. You can do it with a loop:

newlist = []
for elem in s:
    newlist.append(' '.join(x for x in elem.split(' ') if x.lower() == x))

use filter with str.title if you just want the words starting with uppercase letters:

from string import punctuation

s = ["Johnny and Annie.", "She and I."]

print([" ".join(filter(str.istitle,x.translate(None,punctuation).split(" "))) for x in s])
['Johnny Annie', 'She I']

Or use a lambda not x.isupper to remove all lowercase words:

[" ".join(filter(lambda x: not x.isupper(),x.translate(None,punctuation).split(" "))) for x in s]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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