来自文件的 Python 正则表达式表创建器

标签 python regex

我是 Python 编程新手。

我的任务如下:

我有一个巨大的 txt 文件 (20+GB),其中包含大量数据。结构是这样的:

Crap
Crap
Crap
...
Crap
Crap
Useful Data = x y z
Useful Data 2 = x2 y2 z2
Crap
Crap
...
Crap
Crap
Useful Data = x' y' z'
Useful Data 2 = x2' y2' z2'
Crap
Crap...

对于 5000 个对象,依此类推

我必须将每个 x、y 和 z 放入一个文件中,该文件应如下所示:

x y z x2 y2 z2
x' y' z' x2' y2' z2'
x'' y'' z'' x2'' y2'' z2''

......依此类推(我应该有 5000 行)。

我认为正则表达式非常适合这项任务。 我已经写了这篇文章,但我是一个真正的菜鸟,无法继续:

f_in_name="starout.txt"  #input file
f_out_name="cmposvel"    #output file
f_in = open(f_in_name)
for l in f_in:
    if "system_time" in l:
        time=re.compile('^  system_time  =\s+(\S+)')
    elif "com_pos" in l:
        poscm=re.compile('^  com_pos =\s+(\S+)\s+(\S+)\s+(\S+)')
    elif "com_vel" in l:    
        velcm=re.compile('^  com_vel =\s+(\S+)\s+(\S+)\s+(\S+)')
        #how do I write t,x,y,z,vx,vy,vz in the output?

如何在输出中写入 (\S+)?另外,re.compile 仅在当前行还是整个文档中搜索?我很困惑, 有人能帮助我吗?我真的需要这个来制作一个情节,但不知道如何做到这一点。

最佳答案

re.compile 仅准备一个正则表达式以供使用 - 您可以在循环之外执行此操作。这不是它的应用。 “re.search”或“re.match”是要使用的编译表达式的方法。 然后,您将返回匹配项(如果没有,则返回“无”),其中包含您的数据组。

您可以提取组以获取有用的内容。 例如:

my_re = re.compile("stuff=\s+(\S+)\s+(\S+)")
line = "stuff= foo bar"
matches = my_re.search(line)
if matches:
  print(matches.groups())

关于来自文件的 Python 正则表达式表创建器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27111071/

相关文章:

regex - 提取包含一个或多个数字的文件名,然后将 cat 内容提取到输出文件

python - 子模型中的 Django 用户模型

python - DataFrame 挑战 : mapping ID to value in different row. 最好使用 Polars

java - 从字符串中删除非数字和非字符符号

regex - 如何在 Bash 中匹配符号?

javascript - 正则表达式匹配可选组,除非它里面有东西

python - 使用 grpc 向客户端发送服务器错误

python - 单击 : "Got unexpected extra arguments" when passing string

Python子进程.Popen : redirection with ">" does not work

python - 匹配具有相同字符分隔值的日期