nowox
nowox

Reputation: 29066

Manipulation on files with python

I would like to try Python and I am coming from Perl. My first example is a program that:

  1. Read the files passed to the program
  2. Search for a word starting with a vowel that is minimum 4 chars long
  3. Exchange this word with its direct follower
  4. Inverse all the lines in the file (the last line become the first one)
  5. Put everything in uppercase
  6. Display it on stdout

With Perl I can write this:

print reverse map uc s/\b(\w+[aeiouy]\w{3,})\s+(\w+)\b/$2 $1/gr, <>;     

In Python I wrote this:

import fileinput
import re
alist = []
for line in fileinput.input():
    alist.append(re.sub(r"\b(\w+[aeiouy]\w{3,})\s+(\w+)\b", r"\2 \1", line.upper()))
print "".join(alist[::-1])

It it the right way to write it? Why the regex doesn't work here?


Here an example of input file:

Suscipit elementum. Nulla accumsan at ex sed viverra.
molestie. In volutpat aliquam massa, vitae arcu ultricies blandit tempus. Donec nisi semper non
commodo nec purus fringilla fringilla. Suspendisse potenti. Vestibulum feugiat a lectus imperdiet
Class aptent taciti sociosqu ad litora per torquent conubia nostra, per inceptos himenaeos. Cras

Phasellus ac condimentum mauris. Sed aliquet leo sagittis nec varius.

And the expected output:

AC PHASELLUS MAURIS CONDIMENTUM. SED LEO ALIQUET NEC SAGITTIS VARIUS.

CLASS APTENT SOCIOSQU TACITI AD PER LITORA CONUBIA TORQUENT NOSTRA, PER HIMENAEOS INCEPTOS. CRAS
NEC COMMODO FRINGILLA PURUS FRINGILLA. POTENTI SUSPENDISSE. FEUGIAT VESTIBULUM A IMPERDIET LECTUS
MOLESTIE. IN ALIQUAM VOLUTPAT MASSA, ARCU VITAE BLANDIT ULTRICIES TEMPUS. NISI DONEC NON SEMPER
ELEMENTUM SUSCIPIT. ACCUMSAN NULLA AT EX SED VIVERRA.

Upvotes: 1

Views: 50

Answers (1)

vks
vks

Reputation: 67968

alist.append(re.sub(r"\b(\w+[aeiouy]\w{3,})\s+(\w+)\b", r"\2 \1", line.upper(),flags=re.I))

You have to add the igonorecase flag.As you make your line upper or capitals and in your regex you do not account for that.[aeiouy] will match only lower case vowels not uppercase.

Also instead of print use sys.stdout.write as print will add an additional newline.So your file will have an empty line after each line .

Or use

print something.rstrip()

Upvotes: 1

Related Questions