Showing posts with label Python. Show all posts
Showing posts with label Python. Show all posts

Tuesday, August 25, 2020

Python 3: RegEx Back References

Regual Expressions is one of those things that isn't completely regular when switching between languages. This is how you use a back reference in Python.

 
import re

print( re.sub(r'(foo)(bar)',r'\g<2>\g<1>','foobar'))


More info here https://www.regular-expressions.info/replacebackref.html

Monday, August 24, 2020

Python 3: solving 'utf-8' codec can't decode byte 0x92

In Python 3, UTF-8 is the default encoding. In windows you may run into issues where characters will not decode such as 'utf-8' codec can't decode byte 0x92. Use a header with either cp1252 or windows-1252

 

# coding=CP1252
import re

text = """
LADY CAPULET
    Alack the day. She’s dead, she’s dead, she’s dead!
CAPULET
    Ha! Let me see her. Out, alas! She’s cold.
    Her blood is settled, and her joints are stiff.
    Life and these lips have long been separated.
    Death lies on her like an untimely frost
    Upon the sweetest flower of all the field.
Nurse
    O lamentable day!
"""

Wednesday, July 29, 2020

Python: Performing XSLT recursively on a directory of XML files

I've been using https://github.com/ajryan/RptToXml to extract out xml information from Crystal Reports. I then rip through the created xml files with xlst to provide detail information on how the reports are created.  This little python 3.5+ script uses https://www.saxonica.com/download/download_page.xml and will create html files from a directory tree containing xml files.  

TODO: Write an xxl file to convert Crystal Reports to Jasper Reports.


import os
import subprocess
import glob
from pathlib import Path
root_dir = r"C:\crystalxml"
xslFile = r"C:\Saxon\pretty.xsl"

for filename in glob.iglob(root_dir + '/**/*.xml', recursive=True):

 my_parts = filename.split("\\")
 justname = my_parts[-1].split('.')[0]
 my_dir = os.path.dirname(filename)
 newname = fr'{my_dir}\{justname}.html'
 cmd = fr'java -cp C:\Saxon\saxon-he-10.1.jar net.sf.saxon.Transform -t -s:"{filename}" -xsl:{xslFile} -o:"{newname}"'
 subprocess.call(cmd)

Tuesday, May 12, 2020

Python: Learning by starting with the basics.

Just a simple mind exercise in learning a language.  Created a console Hangman game that uses a word api with a hint command that fills in the first available blank.

hangman.py

Guess a Letter:hint
------
|     |
|     0
|    /|\
|    /
t y p h u _ e _ 
Wrong Guesses:lmaio
Guess a Letter:s
------
|     |
|     0
|    /|\
|    /
t y p h u s e s 
Wrong Guesses:lmaio
stay of execution