如何在python类中使用awk脚本?

2024-10-01 07:45:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用python运行awk脚本,以便可以处理一些数据。在

有没有办法让awk脚本在python类中运行而不使用system类作为shell进程调用它?我运行这些python脚本的框架不允许使用子进程调用,所以我要么想办法用python转换awk脚本,要么尽可能用python运行awk脚本。在

有什么建议吗?我的awk脚本基本上是读取一个文本文件,并分离出包含特定化合物的蛋白质块(输出是由我们的框架生成的;我在下面添加了一个如何显示的示例),并将它们分离出来并打印到另一个文件中。在

    buildProtein compoundA compoundB
    begin fusion
    Calculate : (lots of text here on multiple lines)
    (more lines)
    Final result - H20: value CO2: value Compound: value 
    Other Compounds X: Value Y: value Z:value

    [...another similar block]

例如,如果我构建了一个蛋白质,我需要看看化合物的最终结果行中是否有CH3COOH,如果有,我必须从命令“buildProtein”开始,直到下一个块的开始,并将其保存在一个文件中;然后移到下一个,看看它是否还有我要找的复合物…如果没有,我跳到下一个,直到文件的结尾(文件中有我搜索的复合物的多次出现,有时它们是连续的,而有时它们与没有复合物的块交替出现。在

任何帮助都是非常受欢迎的;几个星期以来我一直在努力工作,找到这个网站后,我决定寻求帮助。在

提前谢谢你的好意!在


Tags: 文件数据脚本框架进程value蛋白质shell
3条回答

Python's re module可能会有所帮助,或者,如果您不喜欢使用正则表达式,只需要进行一些快速的字段分隔,则可以使用the built in str ^{}和{a3}函数。在

我刚刚开始学习AWK,所以我不能在这方面提供任何建议。但是,对于某些执行所需操作的python代码:

class ProteinIterator():
    def __init__(self, file):
        self.file = open(file, 'r')
        self.first_line = self.file.readline()
    def __iter__(self):
        return self
    def __next__(self):
        "returns the next protein build"
        if not self.first_line:     # reached end of file
            raise StopIteration
        file = self.file
        protein_data = [self.first_line]
        while True:
            line = file.readline()
            if line.startswith('buildProtein ') or not line:
                self.first_line = line
                break
            protein_data.append(line)
        return Protein(protein_data)

class Protein():
    def __init__(self, data):
        self._data = data
        for line in data:
            if line.startswith('buildProtein '):
                self.initial_compounds = tuple(line[13:].split())
            elif line.startswith('Final result - '):
                pieces = line[15:].split()[::2]   # every other piece is a name
                self.final_compounds = tuple([p[:-1] for p in pieces])
            elif line.startswith('Other Compounds '):
                pieces = line[16:].split()[::2]   # every other piece is a name
                self.other_compounds = tuple([p[:-1] for p in pieces])
    def __repr__(self):
        return ("Protein(%s)"% self._data[0])
    @property
    def data(self):
        return ''.join(self._data)

我们这里有一个buildprotein文本文件的迭代器,它一次返回一个蛋白质作为Protein对象。这个Protein对象足够智能,可以知道它的输入、最终结果和其他结果。如果文件中的实际文本与问题中显示的不完全相同,则可能需要修改一些代码。下面是一个简短的代码测试和示例用法:

^{pr2}$

我没有费心去保存值,但是如果你愿意,你可以把它加进去。希望这能让你振作起来。在

如果不能使用子进程模块,最好的办法是用Python重新编写AWK脚本。为此,fileinput模块是一个很好的转换工具,具有AWK风格。在

相关问题 更多 >