Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/314.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 如何在re.compile()中找到的行之后打印出该行_Python_Parsing - Fatal编程技术网

Python 如何在re.compile()中找到的行之后打印出该行

Python 如何在re.compile()中找到的行之后打印出该行,python,parsing,Python,Parsing,使用此代码 import re file = open('FilePath/OUTPUT.01') lines = file.read() file.close() for match in re.finditer(r"(?m)^\s*-+\s+\S+\s+(\S+)", lines): eng = match.group(1) open('Tmp.txt', 'w').writelines(eng) print match.group(1) 我得到一列如下所示的数据: -1.1266E+05

使用此代码

import re
file = open('FilePath/OUTPUT.01')
lines = file.read()
file.close()
for match in re.finditer(r"(?m)^\s*-+\s+\S+\s+(\S+)", lines):
eng = match.group(1)
open('Tmp.txt', 'w').writelines(eng)
print match.group(1)
我得到一列如下所示的数据:

-1.1266E+05
-1.1265E+05
-1.1265E+05
-1.1265E+05
-1.1264E+05
-1.1264E+05
-1.1264E+05
-1.1263E+05
步骤
-1.1263E+05
-1.1262E+05
-1.1262E+05
-1.1261E+05
-1.1261E+05
-1.1260E+05
-1.1260E+05
-1.1259E+05
步骤
-1.1259E+05
-1.1258E+05
-1.1258E+05
-1.1258E+05
-1.1257E+05
终止。
工程总计
-1.1274E+05
三维

如何将其写入文件(Tmp.txt)?到目前为止,它只写最后一行“3D”。此外,我还想消除所有非x.xxxx形式的行(即仅数字)


i
line
所在的
行的索引,因此
i+1
是下一行:

print lines[i+1]

确保
---
不是最后一行,否则将尝试从不存在的位置读取。此外,正则表达式
\s+-+\s+
要求在
-
s前后都有空格,因为
\s+
表示一个或多个空格;您可能是指
\s*

您可以使用单个正则表达式:

file = open('FilePath/OUTPUT.01')
lines = file.read()
file.close()
with open("output.txt","w") as f:
    for match in re.finditer(r"(?m)^\s*-+\s+\S+\s+(-?[\d.]+E[+-]\d+)", lines):
        f.write(match.group(1)+"\n")
这应该将完全由
-
组成的行之后出现的所有第二个数字写入文件
output.txt

这个正则表达式假设列是空格分隔的,并且第一列永远不会为空

说明:

(?m)                 # allow ^ to match at start of line, not just start of string
^                    # anchor the search at the start of the line
\s*                  # match any leading whitespace
-+                   # match one or more dashes
\s+                  # match trailing whitespace, including linebreak characters
\S+                  # match a run of non-whitespace characters (we're now one line ahead of the dashes
\s+                  # match a run of whitespace
(-?[\d.]+E[+-]\d+)   # match a number in scientific notation

我不想为这个费心。请尝试以下操作:

output = file("tmp.txt", "w")        # open a file for writing
flagged = False                      # when 'flagged == True' we will print the line
for line in file("FilePath/OUTPUT.01"):
    if flagged:
        try:
            result = line.split()[1] # python is zero-indexed!
            print>>output, result    # print to output only if the split worked
        except IndexError:           # otherwise do nothing
            pass
        flagged = False              # but reset the flag
    else:
        if set(line.strip()) == set(["-"]): # does the line consist only of '-'?
            flagged = True           # if so, set the flag to print the next line
这是一个允许您指定行数、偏移量和列数的版本:

OFFSET = 3 # the third line after the `----`
COLUMN = 2 # column index 2

output = file("tmp.txt", "w")
counter = 0                           # 0 evaluates as False
for line in file("FilePath/OUTPUT.01"):
    if counter:                       # any non-zero value evaluates as True
        if counter == OFFSET:
            try:
                result = line.split()[COLUMN] 
                print>>output, result # print to output only if the split worked
            except IndexError:        # otherwise do nothing
                pass
            counter = 0               # reset the flag once you've reached the OFFSET line
        else:
            counter += 1
    else:
        if set(line.strip()) == set(["-"]): # does the line consist only of '-'?
            counter = 1

感谢您对这些行的帮助,但是对于regexp,考虑到我拥有的文件,我希望使用“+”。现在我有了一堆数据列,如何提取每行中的第二项?@Maimon编写一个正则表达式,与行匹配,并在所需部分周围有一个组(例如,
[^]**([^])*
),然后使用
match.group(1)
提取该组我对regexp不太在行(我有其他人帮我做到这一步)。我会在问题中贴一行示例,你可以告诉我你认为我应该怎么做。第二行的数字是如何分开的?用空格、逗号或…?顺便说一下,欢迎使用堆栈溢出!不幸的是,第二个数字不是整数。它们采用科学的表示法:即,'-1.1287E+05'好的,我们需要一些样本来弄清楚如何构造正则表达式。下面是我运行时遇到的错误:回溯(最近一次调用):文件“LineExtract4”,第12行,在?对于re.finditer(r“(?m)^\s*-+\s+\s+\s+(\s+),行:文件“/usr/lib/python2.4/sre.py”,第176行,finditer返回编译(模式,标志)。finditer(字符串)类型错误:预期的字符串或缓冲区,抱歉,忘记从
readlines()
切换到
read()
。更正。@Tim非常感谢你,现在唯一剩下的就是将输出写入一个文件,并删除所有不是数字的行。我将在问题中发布我正在谈论的内容。顺便说一句,编辑您的问题以使其清晰是个好主意,但请注意不要对问题进行太多更改,以免人们的答案不再适用!运行此代码后,我得到以下错误:回溯(最近一次调用last):文件“LineExtract5”,第5行,in?打印>>输出,line.split()[1]索引器错误:列表索引超出范围我认为这可能是因为找到的某些行没有成员。如果“---”行后面的行中没有数字,您希望它做什么?如果要忽略它,可以将
If line.strip():
放在打印行之前,也可以将其包装成
try:。。。除了索引器:…
block。我尝试了这两种方法,但都无法正常运行。我应该把这些行放在哪里,因为我确实想忽略没有数字的行。好的,我已经添加了一个
try
/
,除了上面的
块。