在python中识别大写和小写交替字符

2024-04-26 10:57:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下数据

data['word']

1  Word1
2  WoRdqwertf point
3  lengthy word
4  AbCdEasc
5  Not to be filtered
6  GiBeRrIsH
7  zSxDcFvGnnn

我想找出字符串中大写字母和小写字母交替出现的情况,并删除包含这些单词的行。例如,如果我们看到这里,WoRdqwertf , AbCdEasc, GiBeRrIsH,zSxDcFvGnnn有交替字符,我需要删除这些字符。在

这里的重点是,包含Word1的第一行不应该被删除,因为它只有一个大写字母后跟一个小大写字母。我想删除行只有当它有一个caps,small,caps arrangement或small,caps,small arrangement时。我的输出应该是

^{2}$

有谁能帮助我或者告诉我如何解决这个问题吗?在


Tags: 数据datacaps大写字母字符wordpointsmall
3条回答

可以使用字符串方法。详细->;

l = ['Word1','WoRdqwertf point','lengthy word','AbCdEasc', 'Not to be filtered','GiBeRrIsH', 'zSxDcFvGnnn']

n = []
for section in l:
    new_section = []
    for w in section.split():
        if w == w.title() or w == w.lower():
            new_section.append(w)
    s = ' '.join(new_section)
    if s:
        n.append(s)
    del new_section
print n

一行->

^{pr2}$

输出:

['Word1', 'point', 'lengthy word', 'Not to be filtered']

您可以使用regex ^(?:\w[a-z0-9]*(?: |$))*$

data = ['Word1','WoRdqwertf point','lengthy word','AbCdEasc', 'Not to be filtered','GiBeRrIsH', 'zSxDcFvGnnn']
import re
for line in data:
    if re.search(r'^(?:\w[a-z0-9]*(?: |$))*$', line):
         print (line)

live

您还可以使用filter

data=['Word1','WoRdqwertf point','lengthy word','AbCdEasc','Not to be filtered','GiBeRrIsH','zSxDcFvGnnn']
str_list = filter(lambda item: (item[0].isupper() and item[1:].lower()==item[1:]) or item.islower(), data)
print(list(str_list))
#['Word1', 'lengthy word', 'Not to be filtered'] 

过滤器将只添加小写item.islower()和仅以大写字母(item[0].isupper() and item[1:].lower()==item[1:])开头的项

相关问题 更多 >