python - 来自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。只有所有文件中共有的行。
解决方案
您可以使用正则表达式:
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 模式。
推荐阅读
- c - 修改结构实例的变量
- java - 当用户以全屏模式从 JavaFX 应用程序切换到另一个应用程序时,JavaFX 应用程序在 Mac 上崩溃
- java - Java:如何在不区分大小写的情况下按字母顺序对 ArrayList 进行排序,并在末尾使用任意数量的字符串
- python-3.x - python 3重置游戏弹出
- python - _tkinter.TclError:无法调用“标签”命令:应用程序已被销毁
- javascript - 电子应用程序不会启动,准备就绪时不存在
- python-3.x - 错误:需要 Microsoft Visual C++ 14.0。使用“Microsoft Visual C++ 构建工具”获取它
- javascript - 为什么我的函数在第二次单击时不加载新的类名?
- kubernetes - kubernetes 1.18 堆叠控制平面和 etcd 节点无法添加第二个 ETCD 节点
- sql - 使用 SELECT 结果作为父 SELECT 的列名