gpt4 book ai didi

Python循环遍历字符串并将其与通配符模式匹配

转载 作者:太空宇宙 更新时间:2023-11-03 18:18:04 27 4
gpt4 key购买 nike

string1="abc"
string2="abdabcdfg"

我想查找 string1 是否是 string2 的子字符串。但是,也有通配符,例如 "." 可以是任何字母,y 可以是 "a""d"x 可以是 "b""c"。因此,".yx" 将是 string2 的子字符串。

如何仅使用一个循环对其进行编码?我想循环遍历 string2 并在每个索引处进行比较。我尝试过字典,但我想使用循环我的代码:

def wildcard(string,substring):
sum=""
table={'A': '.', 'C': '.', 'G': '.', 'T': '.','A': 'x', 'T': 'x', 'C': 'y', 'G': 'y'}
for c in strand:
if (c in table) and table[c] not in sum:
sum+=table[c]
elif c not in table:
sum+=c
if sum==substring:
return True
else:
return False

print wildcard("TTAGTTA","xyT.")#should be true

最佳答案

我知道您特别要求使用循环的解决方案。但是,我想采用不同的方法:您可以轻松地将模式转换为 regular expression 。这是一种类似于字符串模式的语言,只是更强大。然后,您可以使用 re 模块检查是否可以在字符串中找到该正则表达式(以及您的子字符串模式)。

def to_regex(pattern, table):
# join substitutions from table, using c itself as default
return ''.join(table.get(c, c) for c in pattern)

import re
symbols = {'.': '[a-z]', '#': '[ad]', '+': '[bc]'}
print re.findall(to_regex('.+#', symbols), 'abdabcdfg')

如果您更喜欢“实际操作”的解决方案,则可以使用循环。

def find_matches(pattern, table, string):
for i in range(len(string) - len(pattern) + 1):
# for each possible starting position, check the pattern
for j, c in enumerate(pattern):
if string[i+j] not in table.get(c, c):
break # character does not match
else:
# loop completed without triggering the break
yield string[i : i + len(pattern)]

symbols = {'.': 'abcdefghijklmnopqrstuvwxyz', '#': 'ad', '+': 'bc'}
print list(find_matches('.+#', symbols, 'abdabcdfg'))

两种情况下的输出都是['abd', 'bcd'],即使用这些替换可以找到两次。

关于Python循环遍历字符串并将其与通配符模式匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24677290/

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