Python如何从列表中的字符串中删除小写单词
我的问题是:如何从作为列表元素的字符串中删除所有小写单词?例如,如果我有以下列表:Python如何从列表中的字符串中删除小写单词,python,string,list,lowercase,Python,String,List,Lowercase,我的问题是:如何从作为列表元素的字符串中删除所有小写单词?例如,如果我有以下列表:s=[“约翰尼和安妮”,“她和我”。] 要使python返回newlist=[“Johnny Annie”,“She I”] 我已经试过了,但遗憾的是它不起作用: def test(something): newlist = re.split("[.]", something) newlist = newlist.translate(None, string.ascii_lowercase)
s=[“约翰尼和安妮”,“她和我”。]
要使python返回newlist=[“Johnny Annie”,“She I”]
我已经试过了,但遗憾的是它不起作用:
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)
您可以使用islower()
和split
逐字迭代来检查单词是否为小写
>>> [' '.join(word for word in i.split() if not word.islower()) for i in s]
['Johnny Annie.', 'She I.']
删除标点符号
>>> import string
>>> [' '.join(word.strip(string.punctuation) for word in i.split() if not word.islower()) for i in s]
['Johnny Annie', 'She I']
在这里,翻译不是正确的工具。您可以通过循环来完成:
newlist = []
for elem in s:
newlist.append(' '.join(x for x in elem.split(' ') if x.lower() == x))
如果只需要以大写字母开头的单词,请将
过滤器
与str.title
一起使用:
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']
或者使用lambda not x.isupper删除所有小写单词:
[" ".join(filter(lambda x: not x.isupper(),x.translate(None,punctuation).split(" "))) for x in s]
迭代列表中的元素并删除小写的单词
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 = 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)