python中的grep

2024-03-29 12:14:52 发布

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

我习惯于在bash中编写脚本,但我也在学习python。 因此,作为一种学习方式,我正在尝试修改python中的一些旧bash。比如说,我有一个文件,行如下:

TOTDOS= 0.38384E+02n_Ef= 0.81961E+02 Ebnd 0.86883E+01

要在bash中获得TOTDOS的值,我只需执行以下操作:

grep "TOTDOS=" 630/out-Dy-eos2|head -c 19|tail -c 11

但是通过python,我在做:

#!/usr/bin/python3
import re
import os.path
import sys

f1 = open("630/out-Dy-eos2", "r")
re1 = r'TOTDOS=\s*(.*)n_Ef=\s*(.*)\sEbnd'
for line in f1:
    match1 = re.search(re1, line)
    if match1:
        TD = (match1.group(1))
f1.close()
print(TD)

这无疑给出了正确的结果,但似乎远不止bash(更不用说regex的问题了)。你知道吗

问题是,我是在python中工作过度,还是缺少了一些东西?你知道吗


Tags: importre脚本bash方式lineouttd
2条回答

[...] but seems to be much more than bash

可能(?)生成器是最接近于shell中使用的“管道过滤”的Python概念。你知道吗

import itertools

#
# Simple generator to iterate through a file
# equivalent of line by line reading from an input file
def source(fname):
    with open(fname,"r") as f:
        for l in f:
            yield l


src = source("630/out-Dy-eos2")

# First filter to keep only lines containing the required word
# equivalent to `grep -F`
filter1 = (l for l in src if "TOTDOS=" in l)

# Second filter to keep only line in the required range
# equivalent of `head -n ... | tail -n ...`
filter2 = itertools.islice(filter1, 10, 20,1)


# Finally output
output = "".join(filter2)
print(output)

关于您的具体示例,如果需要,可以在生成器中使用regexp:

re1 = r'TOTDOS=\s*(.*)n_Ef=\s*(.*)\sEbnd'
filter1 = (m.group(1) for m in (re.match(re1, l) for l in src) if m)

这些只是(部分)基本建筑群可供您使用。你知道吗

与bash行匹配的python脚本更像这样:

with open('630/out-Dy-eos2', 'r') as f1:
    for line in f1:
        if "TOTDOS=" in line:
            print line[8:19]

现在看起来好多了。你知道吗

相关问题 更多 >