DEV Community

pacdev
pacdev

Posted on

Update de fichier

Récemment pour une simulation CFD j'ai eu besoin de faire un offset de mes pièces 3D pour reproduire les pièces dans OpenFoam. C'est l'occas' de mettre en place une modif automatique d'un fichier texte template.

import re

def offset(initial_data, on):

    reg = r'vertex\s\s.+'

    found = re.findall(reg, initial_data)

    for found_reg in found:

        # take only the number
        x, y, z = found_reg.split()[1:]
        x, y, z = float(x), float(y), float(z)

        # add something
        x += on['x']
        y += on['y']
        z += on['z']

        initial_data = initial_data.replace(found_reg, f'vertex  {x:.2E}  {y:.2E}  {z:.2E}')

    return initial_data


if __name__ == "__main__":

    with open('initialePos.txt', 'r') as f:
        initial_data = f.read()

    # on which data to add offset
    on = {"x": 6, "y": 3, "z": 0}

    offset_data = offset(initial_data, on)

    with open('initialPos_offset.txt', 'w') as f:
        f.write(offset_data)
Enter fullscreen mode Exit fullscreen mode
# initialPos.txt
facet normal -1.000000e+00  0.000000e+00  0.000000e+00
   outer loop
     vertex  0.000000e+00  6.666667e-02  0.000000e+00
     vertex  0.000000e+00  0.000000e+00  0.000000e+00
     vertex  0.000000e+00  0.000000e+00  6.666667e-02
   endloop
endfacet

# initialPos_offset.txt
facet normal -1.000000e+00  0.000000e+00  0.000000e+00
   outer loop
     vertex  6.00E+00  3.07E+00  0.00E+00
     vertex  6.00E+00  3.00E+00  0.00E+00
     vertex  6.00E+00  3.00E+00  6.67E-02
   endloop
endfacet
Enter fullscreen mode Exit fullscreen mode

En fait c'est vraiment très basique. On se donne un fichier template dans lequel on va identifier un mot clé ou un pattern (faisable avec une regex). Ici le pattern à trouver est reg = r'vertex\s\s.+'. Il suffit ensuite de définir par quoi on remplace ce qu'on a trouvé au niveau de la regex et on garde toute le reste.

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay