【问题标题】:Python 3.6 - Using re.findall to extract substring from Array-ElementPython 3.6 - 使用 re.findall 从 Array-Element 中提取子字符串
【发布时间】:2018-05-17 10:25:36
【问题描述】:

我已经从 Python 中休息了很长时间,现在我再次需要你的帮助 :)

我有一个如下所示的数组

['>lcl|NC_003078.1_gene_1 [gene=lacE] [locus_tag=SM_b21652] [location=1..1275]\n','>lcl|NC_003078.1_gene_2 [gene=lacF] [locus_tag=SM_b21653] [location=complement(22345..23337)]\n']

该数组包含更多条目,所有条目看起来都与提供的示例相似。我想使用正则表达式提取每个元素的一部分。 我要提取的部分

[location.....]

我使用 Regexr 构建我的正则表达式,并且我尝试过这个:

locationArray=[]
for entry in storageArray:
    location.Array.append((re.findall("(\[location=\d*|complement\(\d*\.\.\d*\)\]|\.\.\d*\]))",str(entry))))
print(locationArray)

在浏览器中使用 Regexr 执行此操作时,Regex 似乎可以解决。

预期/期望的输出:

['[location=...]','[location=...]' etc]

实际输出:

[['cE]', '_b21625]','[location=1','..1257]'],

与输入相比,部分已取自gene 和locus_tag。 我不明白,为什么:(我弄错了数组结构?是关于我的正则表达式吗?

帮助表示赞赏!

尽管如此,这不是我最终想要的输出。提取所有位置后,我想对它们进行处理,结果如下:

Start:     1 End:  1275
Start: 22345 End: 23337

由于我什至没有提取位置部分,所以我已经在这里问了。

感谢您的帮助。我也很欣赏解决问题的不同方法。可能,我的方式不是最好的吗?

【问题讨论】:

  • 你要做的是\[location=[^\]]+\]

标签: python arrays regex python-3.x


【解决方案1】:
import re
a = ['>lcl|NC_003078.1_gene_1 [gene=lacE] [locus_tag=SM_b21652] [location=1..1275]\n','>lcl|NC_003078.1_gene_2 [gene=lacF] [locus_tag=SM_b21653] [location=complement(22345..23337)]\n']
for i in a:
    val = re.findall("location\=.*?]", i)[0]     #Find Location.
    val = re.findall("\d+", val)                 #Find start and end.
    print("Start: {0} End:  {1}".format(val[0], val[1]))

输出:

Start: 1 End:  1275
Start: 22345 End:  23337

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-17
    • 2023-01-07
    • 2016-06-01
    • 1970-01-01
    • 2021-02-03
    • 2018-06-17
    • 2017-04-01
    相关资源
    最近更新 更多