首页 > 解决方案 > 来自txt文件的Python正则表达式

问题描述

我有一个文本文件,里面有数据。

PAS_BEGIN_3600000
    CMD_VERS=2
    CMD_TRNS=O
    CMD_REINIT=
    CMD_OLIVIER=

我想从该文件中提取数据,等号后没有任何内容。

所以在我的新文本文件中,我想得到

CMD_REINIT
CMD_OLIVIER

我该怎么做呢?


我的代码现在就是这样。

import os, os.path

DIR_DAT = "dat"
DIR_OUTPUT = "output"

print("Psst go check in the ouptut folder ;)")
for roots, dir, files in os.walk(DIR_DAT):  
    for filename in files:
        filename_output = "/" + os.path.splitext(filename)[0]   
        with open(DIR_DAT + "/" + filename) as infile, open(DIR_OUTPUT + "/bonjour.txt", "w") as outfile:
            for line in infile:
                if not line.strip().split("=")[-1]:
                    outfile.write(line)

我想在一个文件中收集所有数据。它不起作用。谁能帮我 ?

第三步,它会抓取那个新文件,并且只保留单个值。因为四个文件被附加到一个文件中。有些数据可能存在四、三、两次。

我需要保存一个新文件,我将调用 output.txt。只有所有文件中共有的行。

标签: pythonregex

解决方案


您可以使用正则表达式:

import re

data = """PAS_BEGIN_3600000
    CMD_VERS=2
    CMD_TRNS=O
    CMD_REINIT=
    CMD_OLIVIER="""

found = re.findall(r"^\s+(.*)=\s*$",data,re.M)

print( found )

输出:

['CMD_REINIT', 'CMD_OLIVIER']

表达式寻找

^\s+  line start + whitespaces
(.*)=  anything before a =  which is caputred as group
\s*$   followed by optional whitespaces and line end

使用re.M(多行)标志。

像这样阅读您的文件文本:

with open("yourfile.txt","r") as f:
    data = f.read()

像这样写你的新文件:

with open("newfile.txt","w") as f:
    f.write(''.join("\n",found))

您可以使用http://www.regex101.com来评估 test-text 与 regex-patterns,确保切换到其 python 模式。


推荐阅读