![](/img/trans.png)
[英]Regex in Python to find words that follow pattern: vowel, consonant, vowel, consonant
[英]creating a function to sobstitute binary to words using vowel=0 consonant=1
我正在嘗試創建一個 python 程序來加密(混淆?)一個二進制代碼,以便每個 0 將成為元音,每個 1 成為輔音,並且只有完整含義的單詞:例如,bin 編號 10110 將變成 HELLO . 以下代碼是我編寫的程序,但我找不到執行“加密”的方法
import binascii
#to convert from ascii to bin / from bin to ascii
def text_to_bits(text, encoding='utf-8', errors='surrogatepass'):
bits = bin(int(binascii.hexlify(text.encode(encoding, errors)), 16))[2:]
return bits.zfill(8 * ((len(bits) + 7) // 8))
def text_from_bits(bits, encoding='utf-8', errors='surrogatepass'):
n = int(bits, 2)
return int2bytes(n).decode(encoding, errors)
#making a wordlist
f = open("/home/unkn0wn/PycharmProjects/pythonProject/wordlist.txt","r")
list1 = [line.rstrip('\n') for line in f]
f.close()
vocali = ['a', 'e', 'i', 'o', 'u']
#vowels = 0, consonants = 1
def trasform(word):
lista_parola = list(word)
empty = []
for i in lista_parola:
if i in vocali:
empty.append('0')
else:
empty.append('1')
binar = "".join(empty)
return binar
bin_list = []
for i in list1:
bin_list.append(trasform(i))
#creations of a dict
dizionario = dict(zip(bin_list, list1))
def cript(text):
testo_in_bin = text_to_bits(text)
有什么建議嗎?
我會生成一個字典,將位掩碼映射到可供選擇的相應單詞列表。 假設您有文件words.txt
,它看起來像這樣:
the
quick
brown
fox
jumped
over
lazy
dog
該函數從words.txt
讀取每個單詞,將元音映射到0
並將輔音映射到1
,然后創建並返回一個字典,其鍵是可能的位掩碼,關聯的值是相應單詞的列表。 我在這里做了一些假設——比如文件將只包含小寫字符和一個換行符來分隔單詞。
def generate_mask():
from string import ascii_lowercase as alphabet
vowels = set("aeiou")
consonants = set(alphabet) ^ vowels
mapping = str.maketrans(
"".join(vowels) + "".join(consonants),
("0" * len(vowels)) + ("1" * len(consonants))
)
mask = {}
with open("words.txt", "r") as file:
for word in map(str.rstrip, file):
key = word.translate(mapping)
if key not in mask:
mask[key] = []
mask[key].append(word)
return mask
在這種情況下返回的mask
將是一個字典,它看起來像:
{
'110': ['the'],
'10011': ['quick'],
'11011': ['brown'],
'101': ['fox', 'dog'],
'101101': ['jumped'],
'0101': ['over'],
'1011': ['lazy']
}
>>>
如您所見, fox
和dog
共享相同的位掩碼,因此它們最終位於同一個列表中。
然后,你會像這樣使用它:
def main():
from random import choice
mask = generate_mask()
values = ["101", "1011", "101", "101"]
for value in values:
print(choice(mask[value]))
return 0
if __name__ == "__main__":
import sys
sys.exit(main())
輸出:
dog
lazy
fox
dog
>>>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.