Last active
December 25, 2023 20:06
-
-
Save justinmassiot/9343a7ef3c2b1358cabc12448dbe59d0 to your computer and use it in GitHub Desktop.
Replacements based on advanced regular expressions.\
We also use a temporary file thanks to the 'tempfile' library.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
r''' | |
The script uses regular expressions (regex) to perform replacements on a file. | |
The regex replacement is applied once by line. | |
The search pattern is built like this: | |
(designator)-(pin name)space((prefixes, optional)(component names)) | |
Example: | |
([A-Z]+[0-9]+)-([^ ]+) ((NC_|DNP_)?(2000UF|SS2040FL|DMP1046UFDB|TMP1075DSGR)) | |
^ ^ ^^ ^ match group 5 | |
^ ^ ^^ match group 4 | |
^ ^ ^ match group 3 | |
^ ^ match group 2 | |
^ match group 1 | |
Once a matching line is found, the script checks it has a replacement recipe for | |
this particular pin of this particular component. If yes, the pin identifier is | |
replaced. | |
Need help on regular expressions? | |
https://docs.python.org/3/library/re.html | |
''' | |
import re | |
import tempfile, os | |
optionalNamePrefixes = ( | |
'NC_', | |
'DNP_', | |
) | |
with open('file.txt', 'r') as iFile: | |
with open('mappings.json', 'r') as rFile: | |
replacementsList = json.load(rFile)['clientKey'] | |
with tempfile.NamedTemporaryFile(mode='w', delete=False) as oFile: | |
tmpNetlistFilepath = oFile.name | |
# build the lookup pattern (the part names we're looking after) | |
# the pipe character '|' is a OR operator | |
prefixes = '|'.join(re.escape(prefix) for prefix in optionalNamePrefixes) | |
partNames = '|'.join(re.escape(partName) for partName in replacementsList) | |
lookupPattern = r'^([A-Z]+[0-9]+)-([^ ]+) (({})?({}))'.format(prefixes, partNames) | |
# walk through the file content | |
while True: | |
line = iFile.readline() | |
if not line: | |
break # end of file | |
if re.search(lookupPattern, line): | |
print(f'Match found: {line.rstrip()}\n') | |
try: | |
# rewrite the line by replacing some of the matched groups | |
line = re.sub(lookupPattern, lambda match: f'{match.group(1)}-{replacementsList[match.group(5)][match.group(2)]} {match.group(3)}', line) | |
# inspiration taken from: https://stackoverflow.com/a/14157778 | |
except KeyError: | |
print(f'Can\'t find a replacement instruction\n') | |
finally: | |
oFile.write(line) | |
# move the temporary file to the final location; overwrites an existing file if any | |
os.replace(tmpNetlistFilepath, 'newfile.txt') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment