【问题标题】:Python looping through string and matching it with with wildcard patternPython循环遍历字符串并将其与通配符模式匹配
【发布时间】:2014-08-31 20:56:27
【问题描述】:
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

【问题讨论】:

  • 你应该使用字典循环。在字典中,存储每个符号可以匹配的字符,并在循环中使用它来检查每个字符。
  • 或者,将您的模式转换为正则表达式,例如.+# -> [a-z][bc][ad],然后匹配该正则表达式。我认为这要好得多,但它不使用循环。
  • 能否请您发布您已经编写的代码并描述它有什么问题?
  • 您不能将同一键的多个实例添加到字典中。如果您执行{'A': '.', ..., 'A': 'x'},则A 仅映射到x.,而不是两者。您可以改用'A': '.x''A': ['x','.'];请参阅下面的答案(尽管我以相反的方式进行映射)。

标签: python string loops python-2.7 wildcard


【解决方案1】:

我知道您特别要求使用循环的解决方案。但是,我想另一种方法:您可以轻松地将您的模式转换为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'],即可以使用这些替换找到两次。

【讨论】:

  • 从您现在添加的代码看来,您正在尝试匹配遗传密码,所以这似乎不是功课而是实用的。特别是在这种情况下,我强烈推荐我的第一个解决方案,因为它应该有更好的性能。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-07-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-03
  • 2011-02-28
  • 2012-09-26
相关资源
最近更新 更多