python_examples/rand_char.py

54 lines
1.4 KiB
Python
Raw Permalink Normal View History

2023-08-23 12:02:52 -04:00
#!/usr/bin/env python3
2023-09-16 16:51:31 -04:00
"""rand_char.py
----------------
2023-08-23 12:02:52 -04:00
Generate and Print Random Unicode Characters
2023-09-15 12:55:39 -04:00
This module generates a string of random Unicode characters, specifically
avoiding the surrogate pair range (0xD800 to 0xDFFF). The generated string has
a default length of 5000 characters.
2023-08-23 12:02:52 -04:00
Usage:
2023-09-15 12:55:39 -04:00
Run the script with an argument to specify the length of the string to be
generated: `python script_name.py 5000`
2023-08-23 12:02:52 -04:00
"""
2023-08-23 11:11:51 -04:00
import random
2023-08-23 12:02:52 -04:00
from argparse import ArgumentParser
def generate_string(length):
characters = ""
try:
characters = "".join(
[
chr(
random.choice(
2023-09-15 12:55:39 -04:00
[
i
for i in range(0x0, 0xD7FF + 1)
if i < 0xD800 or i > 0xDFFF
]
2023-08-23 12:02:52 -04:00
)
)
for _ in range(length)
]
)
except UnicodeEncodeError as e:
print(f"Error encoding character: {e}")
2023-09-15 12:55:39 -04:00
return characters
2023-08-23 12:02:52 -04:00
2023-08-23 11:11:51 -04:00
2023-08-23 12:02:52 -04:00
if __name__ == "__main__":
parser = ArgumentParser(
description="Generate a string of random Unicode characters."
)
parser.add_argument(
"length",
type=int,
default=5000,
help="Length of the string to be generated.",
)
args = parser.parse_args()
2023-08-23 11:11:51 -04:00
2023-09-15 12:55:39 -04:00
print(generate_string(args.length))