Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/324.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何基于正则表达式模式从文本文件中提取数据_Python_Regex - Fatal编程技术网

Python 如何基于正则表达式模式从文本文件中提取数据

Python 如何基于正则表达式模式从文本文件中提取数据,python,regex,Python,Regex,我需要一些python程序的帮助。我已经试了很多东西,好几个小时了,但都没用 有人能帮我吗 这就是我需要的: 我有这个文件:它包含了关于蛋白质的信息 我只想过滤与…匹配的蛋白质 从这些蛋白质中,我只需要。。。(6个标记的文本,在sp |之后,以及物种(第二行,在[]之间) 我想把..和..放在..里,最后放在桌子上 到目前为止,我所拥有的: import re def main(): ReadFile() file = open ("file.txt", "r")

我需要一些python程序的帮助。我已经试了很多东西,好几个小时了,但都没用

有人能帮我吗

这就是我需要的:

  • 我有这个文件:它包含了关于蛋白质的信息
  • 我只想过滤与…匹配的蛋白质
  • 从这些蛋白质中,我只需要。。。(6个标记的文本,在sp |之后,以及物种(第二行,在[]之间)
  • 我想把..和..放在..里,最后放在桌子上

到目前为止,我所拥有的:

import re

def main():
    ReadFile()
    file = open ("file.txt", "r")
    FilterOnRegEx(file)

def ReadFile():
    try:
        file = open ("file.txt", "r")
    except IOError:
        print ("File not found!")
    except:
        print ("Something went wrong.")

def FilterOnRegEx(file):
    f = ("[AG].{4}GK[ST]")
    for line in file:
        if f in line:
            print (line)


main()

如果你帮助我,你就是英雄!

我的第一个建议是在打开文件时使用
语句:

with open("ploop.fa", "r") as file:
    FilterOnRegEx(file)
FilterOnRegEx
方法的问题是:
如果ploop在行中
。运算符使用字符串参数在字符串
中搜索
ploop
中的确切文本

相反,您需要将文本表单转换为re对象,然后进行匹配:

def FilterOnRegEx(file):
    ploop = ("[AG].{4}GK[ST]")
    pattern = re.compile(ploop)
    for line in file:
        match = pattern.search(line)
        if match is not None:
            print (line)
这将帮助你前进

作为下一步,我建议学习。打印匹配的行非常好,但这无助于您对它们进行进一步的操作。我可能会将
print
更改为
yield
,这样我就可以进一步处理数据,例如提取所需的部分并重新格式化以供输出

作为一个简单的演示:

def FilterOnRegEx(file):
    ploop = ("[AG].{4}GK[ST]")
    pattern = re.compile(ploop)
    for line in file:
        match = pattern.search(line)
        if match is not None:
            yield line

with open("ploop.fa", "r") as file:
    for line in FilterOnRegEx(file):
        print(line)



附录:我运行了上面我发布的代码,使用了您发布的数据样本,它成功地打印了一些行,而不是其他行。换句话说,正则表达式确实匹配了一些行,但不匹配其他行。到目前为止还不错。但是,您需要的数据并不是全部在输入中的一行上!这意味着过滤图案上的单个线条不够。(当然,除非我在问题中没有看到正确的换行符)数据的方式,你需要实现一个更健壮的解析器,用状态来知道一个记录何时开始,当一个记录结束,一个给定的行在一个记录的中间。

< p>这似乎对你的示例文本起作用。我不知道你是否可以有一个以上的每个文件的提取,而且我已经不在这里了,所以你必须如果需要,请扩展它:

#!python3
import re

Extract = {}

def match_notes(line):
    global _State
    pattern = r"^\s+(.*)$"
    m = re.match(pattern, line.rstrip())
    if m:
        if 'notes' not in Extract:
            Extract['notes'] = []

        Extract['notes'].append(m.group(1))
        return True
    else:
        _State = match_sp
        return False

def match_pattern(line):
    global _State
    pattern = r"^\s+Pattern: (.*)$"
    m = re.match(pattern, line.rstrip())
    if m:
        Extract['pattern'] = m.group(1)
        _State = match_notes
        return True
    return False

def match_sp(line):
    global _State
    pattern = r">sp\|([^|]+)\|(.*)$"
    m = re.match(pattern, line.rstrip())
    if m:
        if 'sp' not in Extract:
            Extract['sp'] = []
        spinfo = {
            'accession code': m.group(1),
            'other code': m.group(2),
        }
        Extract['sp'].append(spinfo)
        _State = match_sp_note
        return True
    return False

def match_sp_note(line):
    """Second line of >sp paragraph"""
    global _State
    pattern = r"^([^[]*)\[([^]]+)\)"
    m = re.match(pattern, line.rstrip())
    if m:
        spinfo = Extract['sp'][-1]
        spinfo['note'] = m.group(1).strip()
        spinfo['species'] = m.group(2).strip()
        spinfo['sequence'] = ''
        _State = match_sp_sequence
        return True
    return False

def match_sp_range(line):
    """Last line of >sp paragraph"""
    global _State
    pattern = r"^\s+(\d+) - (\d+):\s+(.*)"
    m = re.match(pattern, line.rstrip())
    if m:
        spinfo = Extract['sp'][-1]
        spinfo['range'] = (m.group(1), m.group(2))
        spinfo['flags'] = m.group(3)
        _State = match_sp
        return True
    return False

def match_sp_sequence(line):
    """Middle block of >sp paragraph"""
    global _State

    spinfo = Extract['sp'][-1]

    if re.match("^\s", line):
        # End of sequence. Check for pattern, reset state for sp
        if re.match(r"[AG].{4}GK[ST]", spinfo['sequence']):
            spinfo['ag_4gkst'] = True
        else:
            spinfo['ag_4gkst'] = False

        _State = match_sp_range
        return False

    spinfo['sequence'] += line.rstrip()
    return True

def match_start(line):
    """Start of outer item"""
    global _State
    pattern = r"^Hits for ([A-Z]+\d+)|([^:]+) : (?:\[occurs (\w+)\])?"
    m = re.match(pattern, line.rstrip())
    if m:
        Extract['pattern_id'] = m.group(1)
        Extract['title'] = m.group(2)
        Extract['occurrence'] = m.group(3)
        _State = match_pattern
        return True
    return False

_State = match_start

def process_line(line):
    while True:
        state = _State
        if state(line):
            return True

        if _State is not state:
            continue

        if len(line) == 0:
            return False

        print("Unexpected line:", line)
        print("State was:", _State)
        return False

def process_file(filename):
    with open(filename, "r") as infile:
        for line in infile:
            process_line(line.rstrip())

process_file("ploop.fa")
import pprint
pprint.pprint(Extract)

看起来您希望我们为您编写一些代码。虽然许多用户愿意为陷入困境的编码人员编写代码,但他们通常只在海报已经尝试自己解决问题时提供帮助。演示这一努力的一个好方法是包含您迄今为止编写的代码,例如输入(如果有),预期输出,以及您实际获得的输出(控制台输出、回溯等)。您提供的详细信息越多,您可能收到的答案就越多。请查看and。您好,欢迎访问SO。请阅读:)您可能会被否决,因为人们有时不太欢迎您,但不要太担心这一点。更新你的问题,或者创建一个新的问题,用你迄今为止尝试过的最好的东西和你遇到的问题。我相信你会得到帮助的,已经编辑好了。但是我被困在正则表达式函数中,所以我没有太多的代码。并不是说我什么都没试过,我试了很多东西,一个小时又一个小时,但都不管用。但它是经过编辑的!你能检查数据文件的链接吗?它似乎不起作用-可能需要“公开”?简单地说,您需要使用
re.compile()
并搜索正则表达式,而不是
中的
。谢谢您的解释!事实上,这是可行的。在学校里从未学过关于产量的知识,但事实上,它是有用的。很高兴知道正则表达式可以工作。但是现在脚本必须打印所有属于与RE匹配的行的行。(因此,如果蛋白质序列中存在匹配项,它必须打印文件中关于这些蛋白质的所有信息)。在那之后,我必须获取加入代码(
Q6GZX2
在第一个蛋白质中),以及物种(
青蛙病毒3(分离的古尔哈病毒)(FV-3)
在第一个蛋白质中)。1/2你认为用列表中的一个列表(一个蛋白质列表,由每两个换行符分隔,包含信息列表,包括登录代码和物种)来实现这一点是一个好主意,还是有更好的方法?我个人会先为一个记录创建一个数据结构,然后为该文件创建一个解析器。我发现,当我为数据创建一个类时,管理代码要比跟踪列表列表以及每个索引在每个级别的含义更容易。每组行(“记录”)是否由两个换行分隔?如果是这样的话,那么这将使您的生活变得更轻松(因为整个文件一次就可以放入内存中)。对于这样一个特定用途的程序,我只需一次读取整个文件(,然后获取记录列表。然后应用匹配并处理匹配的字符串。在“真实世界”我不会这样做,这样我就可以处理更多的数据。是的,我在谷歌上搜索时已经读到了一些关于类的内容。但是它看起来有点复杂。像这样的脚本的类的基础是什么?然后也许我可以扩展它。感谢代码!我已经尝试过了,它不是我需要的表,但我想我可以用它来完成最终的代码首先我得到了一些带有错误()的行,然后我得到了带有其他数据()的蛋白质。但是很高兴看到数据(登录代码等)在一个单独的行上,带有一个名称!谢谢
#!python3
import re

Extract = {}

def match_notes(line):
    global _State
    pattern = r"^\s+(.*)$"
    m = re.match(pattern, line.rstrip())
    if m:
        if 'notes' not in Extract:
            Extract['notes'] = []

        Extract['notes'].append(m.group(1))
        return True
    else:
        _State = match_sp
        return False

def match_pattern(line):
    global _State
    pattern = r"^\s+Pattern: (.*)$"
    m = re.match(pattern, line.rstrip())
    if m:
        Extract['pattern'] = m.group(1)
        _State = match_notes
        return True
    return False

def match_sp(line):
    global _State
    pattern = r">sp\|([^|]+)\|(.*)$"
    m = re.match(pattern, line.rstrip())
    if m:
        if 'sp' not in Extract:
            Extract['sp'] = []
        spinfo = {
            'accession code': m.group(1),
            'other code': m.group(2),
        }
        Extract['sp'].append(spinfo)
        _State = match_sp_note
        return True
    return False

def match_sp_note(line):
    """Second line of >sp paragraph"""
    global _State
    pattern = r"^([^[]*)\[([^]]+)\)"
    m = re.match(pattern, line.rstrip())
    if m:
        spinfo = Extract['sp'][-1]
        spinfo['note'] = m.group(1).strip()
        spinfo['species'] = m.group(2).strip()
        spinfo['sequence'] = ''
        _State = match_sp_sequence
        return True
    return False

def match_sp_range(line):
    """Last line of >sp paragraph"""
    global _State
    pattern = r"^\s+(\d+) - (\d+):\s+(.*)"
    m = re.match(pattern, line.rstrip())
    if m:
        spinfo = Extract['sp'][-1]
        spinfo['range'] = (m.group(1), m.group(2))
        spinfo['flags'] = m.group(3)
        _State = match_sp
        return True
    return False

def match_sp_sequence(line):
    """Middle block of >sp paragraph"""
    global _State

    spinfo = Extract['sp'][-1]

    if re.match("^\s", line):
        # End of sequence. Check for pattern, reset state for sp
        if re.match(r"[AG].{4}GK[ST]", spinfo['sequence']):
            spinfo['ag_4gkst'] = True
        else:
            spinfo['ag_4gkst'] = False

        _State = match_sp_range
        return False

    spinfo['sequence'] += line.rstrip()
    return True

def match_start(line):
    """Start of outer item"""
    global _State
    pattern = r"^Hits for ([A-Z]+\d+)|([^:]+) : (?:\[occurs (\w+)\])?"
    m = re.match(pattern, line.rstrip())
    if m:
        Extract['pattern_id'] = m.group(1)
        Extract['title'] = m.group(2)
        Extract['occurrence'] = m.group(3)
        _State = match_pattern
        return True
    return False

_State = match_start

def process_line(line):
    while True:
        state = _State
        if state(line):
            return True

        if _State is not state:
            continue

        if len(line) == 0:
            return False

        print("Unexpected line:", line)
        print("State was:", _State)
        return False

def process_file(filename):
    with open(filename, "r") as infile:
        for line in infile:
            process_line(line.rstrip())

process_file("ploop.fa")
import pprint
pprint.pprint(Extract)