我正在尝试在python中编写代码,这将帮助我查找两个特定字符串之间的字符串。当我用一个字符串实现代码时,我得到了所需的输出。但是,我需要匹配序列数组中的模式。它一直在给我一个错误。
import re
def find_between(prefix, suffix, text):
pattern = r"{}\s*(.*)\s*{}".format(re.escape(prefix), re.escape(suffix))
result = re.search(pattern, text, re.DOTALL)
if result:
return result.group(1)
else:
return None
text = "AGGTCCTGTAAACCT"
prefix = "TCCT"
suffix = "ACCT"
find_between(prefix, suffix, text)
输出:' GTAA'
seqs = readFastq('FN1.fastq')
text = seqs
prefix = "TCCT"
suffix = "ACCT"
find_between(prefix, suffix, text)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-26-9c35672e7561> in <module>()
2 prefix = "TCCT"
3 suffix = "ACCT"
----> 4 find_between(prefix, suffix, text)
<ipython-input-19-5f42599c717f> in find_between(prefix, suffix, text)
3 def find_between(prefix, suffix, text):
4 pattern = r"{}\s*(.*)\s*{}".format(re.escape(prefix), re.escape(suffix))
----> 5 result = re.search(pattern, text, re.DOTALL)
6 if result:
7 return result.group(1)
/Users/shravantikrishna/anaconda/lib/python3.6/re.py in search(pattern, string, flags)
180 """Scan through string looking for a match to the pattern, returning
181 a match object, or None if no match was found."""
--> 182 return _compile(pattern, flags).search(string)
183
184 def sub(pattern, repl, string, count=0, flags=0):
TypeError: expected string or bytes-like object
答案 0 :(得分:0)
在这个看似简单的情况下,我不会使用正则表达式进行匹配。如果您有兴趣在前缀和后缀之间找到文本,可以使用: result = text.lstrip(prefix [:2])。rstrip(suffix [:2]) 但是你没有说出前缀和后缀中你不需要匹配哪两个字符。
以下是一些示例代码和数据......
text = 'XXsome data that needs to be parsedXX'
prefix = 'XXYY'
suffix = 'XXYY'
result = text.lstrip(prefix[:2]).rstrip(suffix[:2])
print(result)
some data that needs to be parsed