簡體   English   中英

Python:在大寫字母前查找小寫/數字的正則表達式條件

[英]Python: regex condition to find lower case/digit before capital letter

我想在 python 中拆分一個字符串並將其放入字典中,這樣一個鍵是兩個大寫字母之間的任何字符塊,值應該是這些塊在字符串中的出現次數。

例如: string = 'ABbACc1Dd2E'應該返回: {'A': 2, 'Bb': 1, 'Cc1': 1, 'Dd2': 1, 'E': 1}

到目前為止,我已經找到了兩個可行的解決方案(見下文),但我正在尋找一個更通用/更優雅的解決方案,可能是單行正則表達式條件。

謝謝

解決方案1

string = 'ABbACc1Dd2E'
string = ' '.join(string)

for ii in re.findall("([A-Z] [a-z])",string) + \
          re.findall("([A-Z] [0-9])",string) + \
          re.findall("([a-x] [0-9])",string):
            new_ii = ii.replace(' ','')
            string = string.replace(ii, new_ii)

string = string.split()
all_dict = {}
for elem in string:
    all_dict[elem] = all_dict[elem] + 1 if elem in all_dict.keys() else 1 

print(all_dict)

{'A': 2, 'Bb': 1, 'Cc1': 1, 'Dd2': 1, 'E': 1}

解決方案2

string = 'ABbACc1Dd2E'
all_upper = [ (pos,char) for (pos,char) in enumerate(string) if char.isupper() ]

all_dict = {}
for (pos,char) in enumerate(string):
    if (pos,char) in all_upper:
        new_elem = char
    else:
        new_elem += char

    if pos < len(string) -1 :
        if  string[pos+1].isupper():
            all_dict[new_elem] = all_dict[new_elem] + 1 if new_elem in all_dict.keys() else 1 
        else:
            pass
    else:
        all_dict[new_elem] = all_dict[new_elem] + 1 if new_elem in all_dict.keys() else 1 

print(all_dict)

{'A': 2, 'Bb': 1, 'Cc1': 1, 'Dd2': 1, 'E': 1}

感謝usr2564301提出這個建議:

正確的正則表達式是'[AZ][az]*\\d*'

import re

string = 'ABbACc1Dd2E'
print(re.findall(r'[A-Z][a-z]*\d*', string))
['A', 'Bb', 'A', 'Cc1', 'Dd2', 'E']

然后可以使用itertools.groupby制作一個迭代器,該迭代器從可迭代對象中返回連續的鍵和組。

from itertools import groupby

all_dict = {}
for i,j in groupby(re.findall(r'[A-Z][a-z]*\d*', string)):
    all_dict[i] = all_dict[i] + 1 if i in all_dict.keys() else 1 
print(all_dict)
{'A': 2, 'Bb': 1, 'Cc1': 1, 'Dd2': 1, 'E': 1}

最終,可以使用sorted()將其與正確的計數合並為一行:

print({i:len(list(j)) for i,j in groupby(sorted(re.findall(r'[A-Z][a-z]*\d*', string))) })
{'A': 2, 'Bb': 1, 'Cc1': 1, 'Dd2': 1, 'E': 1}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM