Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Regex help for newbie
#4
It seems to me that if you are looking for certain strings it will be easier without regex

I am not familiar with Python 2 syntax therefore I use Python 3 code:

with open('cars.txt', 'r') as source:
    cars = ['[cars]\n']
    trucks = ['[trucks]\n']
    for row in source:
        if 'car' in row:
            cars.append(row)
        elif 'truck' in row:
            trucks.append(row)

with open('cars_result.txt', 'w') as filtered:
    print(*cars, *trucks, file=filtered)
cars_result.txt will look like:

Output:
[cars] car1 car2 [trucks] truck1 truck12 truck13
Ansible is not my cup of tea but quick check of documentation revealed statements about support of Python 3.

In your code you use old-style open and 'with open(...'. What is the reason of such mix?
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply


Messages In This Thread
Regex help for newbie - by mcmpdx - Jul-01-2019, 12:15 AM
RE: Regex help for newbie - by scidam - Jul-01-2019, 01:07 AM
RE: Regex help for newbie - by mcmpdx - Jul-01-2019, 02:35 AM
RE: Regex help for newbie - by perfringo - Jul-01-2019, 06:54 AM
RE: Regex help for newbie - by mcmpdx - Jul-01-2019, 04:50 PM
RE: Regex help for newbie - by ichabod801 - Jul-01-2019, 06:17 PM
RE: Regex help for newbie - by mcmpdx - Jul-01-2019, 10:21 PM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020