如何实现文本预处理后通过双字符迭代与二维数组列交换加密?
Got it, let's walk through building this text encryption program step by step. I'll use Python for examples since it's super intuitive for string handling and array operations, but the core logic works for any language you prefer.
Let's make sure we're aligned on what we need to build:
- Load a text file, strip out all non-alphabet characters (spaces, periods, commas, etc.)
- Store the cleaned characters in an array
- Use a 2D array split into 4 separate quadrants to process character pairs: either swap their columns or replace them with other characters based on their quadrant positions
- Output the final encrypted text
First, we need to read the input file and filter out everything that isn't a letter. I'll standardize all characters to uppercase (you could use lowercase too—just pick one and stick with it to avoid confusion later).
def load_and_clean_text(file_path): # Read the input file with open(file_path, 'r', encoding='utf-8') as f: raw_text = f.read() # Keep only letters, convert to uppercase cleaned_chars = [char.upper() for char in raw_text if char.isalpha()] return cleaned_chars
This function takes a file path, reads the content, and returns an array of only uppercase letters—no extra junk.
We'll use a 5x5 grid (common in classic ciphers like Playfair) since it fits all 26 letters if we merge I and J (you can adjust this if you need to keep them separate, like using a 6x6 grid). Then we'll split this grid into 4 quadrants based on row/column positions.
def build_quadrant_array(): # Merge I and J to fit in 5x5 grid alphabet = "ABCDEFGHIKLMNOPQRSTUVWXYZ" quad_array = [] # Split alphabet into 5 rows of 5 characters each for i in range(5): row = list(alphabet[i*5 : (i+1)*5]) quad_array.append(row) return quad_array # Helper function to find a character's (row, column) position in the grid def get_char_position(quad_array, char): for row_idx, row in enumerate(quad_array): if char in row: col_idx = row.index(char) return (row_idx, col_idx) # If we get a J, return I's position (since we merged them) return get_char_position(quad_array, 'I')
The quadrant breakdown here is simple:
- Quadrant 1: Rows 0-1, Columns 0-1 (top-left)
- Quadrant 2: Rows 0-1, Columns 2-4 (top-right)
- Quadrant 3: Rows 2-4, Columns 0-1 (bottom-left)
- Quadrant 4: Rows 2-4, Columns 2-4 (bottom-right)
Now for the core encryption logic. We'll process characters two at a time—if we have an odd number of characters, we'll add a filler (like 'X') to make a full pair. The rules I'll implement are:
- Same quadrant: Swap the columns of the two characters to get new encrypted characters
- Diagonal quadrants (1↔4, 2↔3): Swap row and column positions for each character
- Adjacent quadrants (1↔2, 1↔3, 2↔4, 3↔4): Keep the row the same, swap columns to the corresponding position in the adjacent quadrant
def encrypt_pair(quad_array, char1, char2): r1, c1 = get_char_position(quad_array, char1) r2, c2 = get_char_position(quad_array, char2) # Helper to determine which quadrant a character is in def get_quadrant(row, col): if row < 2 and col < 2: return 1 elif row < 2 and col >= 2: return 2 elif row >= 2 and col < 2: return 3 else: return 4 q1 = get_quadrant(r1, c1) q2 = get_quadrant(r2, c2) # Apply encryption rules if q1 == q2: # Same quadrant: swap columns new_char1 = quad_array[r1][c2] new_char2 = quad_array[r2][c1] elif (q1, q2) in [(1,4), (4,1), (2,3), (3,2)]: # Diagonal quadrants: swap row and column new_char1 = quad_array[c1][r1] new_char2 = quad_array[c2][r2] else: # Adjacent quadrants: shift columns to adjacent quadrant new_c1 = c1 + 2 if q1 == 1 else c1 - 2 if q1 == 2 else c1 new_c2 = c2 + 2 if q2 == 3 else c2 - 2 if q2 == 4 else c2 new_char1 = quad_array[r1][new_c1] new_char2 = quad_array[r2][new_c2] return (new_char1, new_char2) def process_all_chars(cleaned_chars, quad_array): encrypted_chars = [] # Add filler if odd number of characters if len(cleaned_chars) % 2 != 0: cleaned_chars.append('X') # Process pairs one by one for i in range(0, len(cleaned_chars), 2): ec1, ec2 = encrypt_pair(quad_array, cleaned_chars[i], cleaned_chars[i+1]) encrypted_chars.append(ec1) encrypted_chars.append(ec2) # Join array into a single string for output return ''.join(encrypted_chars)
Put all the pieces together into a runnable script. You can adjust the input/output file paths as needed.
def load_and_clean_text(file_path): with open(file_path, 'r', encoding='utf-8') as f: raw_text = f.read() cleaned_chars = [char.upper() for char in raw_text if char.isalpha()] return cleaned_chars def build_quadrant_array(): alphabet = "ABCDEFGHIKLMNOPQRSTUVWXYZ" quad_array = [] for i in range(5): row = list(alphabet[i*5 : (i+1)*5]) quad_array.append(row) return quad_array def get_char_position(quad_array, char): for row_idx, row in enumerate(quad_array): if char in row: col_idx = row.index(char) return (row_idx, col_idx) return get_char_position(quad_array, 'I') def encrypt_pair(quad_array, char1, char2): r1, c1 = get_char_position(quad_array, char1) r2, c2 = get_char_position(quad_array, char2) def get_quadrant(row, col): if row < 2 and col < 2: return 1 elif row < 2 and col >= 2: return 2 elif row >= 2 and col < 2: return 3 else: return 4 q1 = get_quadrant(r1, c1) q2 = get_quadrant(r2, c2) if q1 == q2: new_char1 = quad_array[r1][c2] new_char2 = quad_array[r2][c1] elif (q1, q2) in [(1,4), (4,1), (2,3), (3,2)]: new_char1 = quad_array[c1][r1] new_char2 = quad_array[c2][r2] else: new_c1 = c1 + 2 if q1 == 1 else c1 - 2 if q1 == 2 else c1 new_c2 = c2 + 2 if q2 == 3 else c2 - 2 if q2 == 4 else c2 new_char1 = quad_array[r1][new_c1] new_char2 = quad_array[r2][new_c2] return (new_char1, new_char2) def process_all_chars(cleaned_chars, quad_array): encrypted_chars = [] if len(cleaned_chars) % 2 != 0: cleaned_chars.append('X') for i in range(0, len(cleaned_chars), 2): ec1, ec2 = encrypt_pair(quad_array, cleaned_chars[i], cleaned_chars[i+1]) encrypted_chars.append(ec1) encrypted_chars.append(ec2) return ''.join(encrypted_chars) if __name__ == "__main__": # Replace with your input file path input_file = "input.txt" # Replace with your desired output file path (optional) output_file = "encrypted_output.txt" cleaned_text = load_and_clean_text(input_file) cipher_grid = build_quadrant_array() encrypted_text = process_all_chars(cleaned_text, cipher_grid) # Print to console print("Encrypted Text:\n", encrypted_text) # Write to file with open(output_file, 'w', encoding='utf-8') as f: f.write(encrypted_text)
- Adjust Quadrant Rules: You can change how the 2D array is split into quadrants (e.g., 6x6 grid for case-sensitive encryption)
- Modify Encryption Logic: Swap columns with rows, shift characters within the quadrant, or use different mapping rules for cross-quadrant pairs
- Add Decryption: Reverse the encryption rules (e.g., if you swapped columns for same-quadrant pairs, swap them back to decrypt)
- Handle Case Sensitivity: Track the original case of each character during preprocessing, then restore it after encryption
内容的提问来源于stack exchange,提问作者Kevin Niland

