【问题标题】:How can I search a string for any occurrence of substring (including partial matches) in python?如何在 python 中搜索字符串以查找任何出现的子字符串(包括部分匹配)?
【发布时间】:2019-03-28 10:47:16
【问题描述】:

我正在尝试编写一个程序,该程序将搜索一系列字符串并在找到子字符串的任何部分时返回 true。

比如说我感兴趣的子串是:

GATCGATC

程序应为以下情况返回 True:

GGTGGATCGATC

并且还应该返回 true for(因为它以 GATC 结尾):

GGTGTTTTGATC

到目前为止我有:

def matchpat(str1, str2):
    '''Find a pattern in a string'''
    if str1 in str2:
        return True
    else:
        return False

此函数有效,但只有当整个模式存在时,它才会返回 False 部分匹配。

【问题讨论】:

  • 部分匹配,特别是任何阈值?因为匹配的字母也是部分匹配
  • 请澄清您的任务:“找到子字符串的任何部分” - 该部分应该有多大?一个字母算作字符串的一部分吗?或者我们是否看到“GATCGATC”重复“GATC”子字符串这一事实?
  • 请发布TrueFalse 案例的样本。
  • 所以句子This is not working也应该返回TRUE,因为它以GATCGATC的子串结尾? (句子中包含字母G,是GATCGATC的子串)
  • 是的,如果字符串以部分匹配结尾,即使是单个 G,那么它应该返回 True。

标签: python python-3.x


【解决方案1】:

您好,我编写了这个有效的代码。 您可以使用变量将其更改为更具动态性

text = 'GGTGGATCGATC'
lookingFor = 'GATCGATC'

def method():
  print('in check')
  if lookingFor in text:
    return true
  else:
    return false

def main():
  method()
  if __name__ == "__main__":

如果你想让方法接受输入,你可以在方法定义中传递它:

def method(text, lookingFor)

【讨论】:

  • 代码中有很多错别字,但它有效:-)。 def method():TrueFalsedef下方缩进
【解决方案2】:

我使用了一个名为 Fuzzywuzzy 的库来解决类似的问题,它非常适合我的要求并且可能会有所帮助。

它使用Levenshtein distance 度量来比较字符串。

【讨论】:

  • 感谢您的建议,但我想尝试在不导入任何模块的情况下编写代码。
【解决方案3】:

您可以使用re module 来做到这一点

import re

patterntomatch = "GATCGATC"
patterntomatch = "[{0}]".format(patterntomatch)

TextTomatch = "This is something"

matchObj = re.match(patterntomatch,TextTomatch,re.I)

if matchObj:
    print ("match found")
else:
    print("no match found")

【讨论】:

    猜你喜欢
    • 2020-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-09
    相关资源
    最近更新 更多