-
Notifications
You must be signed in to change notification settings - Fork 0
/
unicode-escape-decode.py
55 lines (42 loc) · 1.85 KB
/
unicode-escape-decode.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
"""
Script Name: unicode-escape-decode.py
Author: Justin Lund
Last modified: 04/16/24
Date created: 08/17/23
Version: 1.2.1
Purpose:
Decodes unicode escape sequences
Usage examples:
python3 unicode-decode.py -i input.txt -p
python3 unicode-decode.py -i input.txt -o decoded_unicode.txt
"""
import re
import argparse
def replace_unicode_escape(match):
# Replace the unicode escape sequence with the corresponding character
return chr(int(match.group(1), 16))
def decode_unicode_escapes(input_file, output_file, print_output):
# Read the file
with open(input_file, 'r', encoding='utf-8') as file:
content = file.read()
# Use a regular expression to find and decode the escape sequences
decoded_content = re.sub(r'\\u([0-9a-fA-F]{4})', replace_unicode_escape, content)
# Encode to bytes and decode back to string, replacing problematic characters
decoded_content = decoded_content.encode('utf-8', 'replace').decode()
if output_file:
# Write the decoded content to the new file
with open(output_file, 'w', encoding='utf-8') as file:
file.write(decoded_content)
print(f"Decoded data has been written to {output_file}")
if print_output or not output_file:
# Print the decoded content
print(decoded_content)
def main():
parser = argparse.ArgumentParser(description="Decode Unicode escape sequences")
parser.add_argument("-i", "--input", required=True, help="Input file with the encoded content")
parser.add_argument("-o", "--output", help="Output file to save the decoded content to")
parser.add_argument("-p", "--print", action="store_true", help="Print the output on screen instead of writing to an output file, unless -o also specified")
args = parser.parse_args()
decode_unicode_escapes(args.input, args.output, args.print)
if __name__ == "__main__":
main()