gpt4 book ai didi

python - 使用正则表达式查找字符串中的所有小写字母附加到列表。 Python

转载 作者:行者123 更新时间:2023-12-01 05:46:49 26 4
gpt4 key购买 nike

我正在寻找一种方法,从同时包含大写和可能小写字母的字符串中获取小写值

这是一个例子

sequences = ['CABCABCABdefgdefgdefgCABCAB','FEGFEGFEGwowhelloFEGFEGonemoreFEG','NONEARELOWERCASE'] #sequences with uppercase and potentially lowercase letters

这就是我想要输出的内容

upper_output = ['CABCABCABCABCAB','FEGFEGFEGFEGFEGFEG','NONEARELOWERCASE'] #the upper case letters joined together
lower_output = [['defgdefgdefg'],['wowhello','onemore'],[]] #the lower case letters in lists within lists
lower_indx = [[9],[9,23],[]] #where the lower case values occur in the original sequence

所以我希望 lower_output 列表是子列表的列表。子列表将包含所有小写字母的字符串。

我正在考虑使用正则表达式。 。 。

import re

lower_indx = []

for seq in sequences:
lower_indx.append(re.findall("[a-z]", seq).start())

print lower_indx

对于我正在尝试的小写列表:

lower_output = []

for seq in sequences:
temp = ''
temp = re.findall("[a-z]", seq)
lower_output.append(temp)

print lower_output

但这些值不在单独的列表中(我仍然需要加入它们)

[['d', 'e', 'f', 'g', 'd', 'e', 'f', 'g', 'd', 'e', 'f', 'g'], ['w', 'o', 'w', 'h', 'e', 'l', 'l', 'o', 'o', 'n', 'e', 'm', 'o', 'r', 'e'], []]

最佳答案

听起来(我可能误解了你的问题)你只需要捕获小写字母的运行,而不是每个单独的小写字母。这很简单:只需将 + 量词添加到正则表达式中即可。

for seq in sequences:
lower_output.append(re.findall("[a-z]+", seq)) # add substrings

+ 量词指定您想要“至少一个,并且在一行中可以找到尽可能多的”前面的表达式(在本例中 '[a-z]')。因此,这将捕获一组中所有小写字母的完整运行,这将使它们按照您希望的方式显示在输出列表中。

如果你想保留你的列表结构并获取索引,它会变得有点大丑陋,但它仍然非常简单:

for seq in sequences:
matches = re.finditer("[a-z]+", seq) # List of Match objects.
lower_output.append([match.group(0) for match in matches]) # add substrings
lower_indx.append([match.start(0) for match in matches]) # add indices

print lower_output
>>> [['defgdefgdefg'], ['wowhello', 'onemore'], []]

print lower_indx
>>> [[9], [9, 23], []]

关于python - 使用正则表达式查找字符串中的所有小写字母附加到列表。 Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15821613/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com