简体   繁体   English

Python,混淆列表中的字母

[英]Python, obfuscating letters in a list

I have created a list characters = list(original.lower()) to list an input of a four letter word. 我创建了一个列表characters = list(original.lower())来列出四个字母单词的输入。 This breaks down the input into sepearte characters and makes them all lowercase. 这会将输入分解为单独的字符并使它们全部变为小写。

In a following function I need to call each letter that was seperated and replace them with 1 of 5 set ascii chars which are ! 在以下函数中,我需要调用每个分隔的字母,并用5个set ascii字符中的1个替换它们! % * # @ %*#@

I have created the list into a var called - obfuscate = ["!", "%", "*", "#", "@"] and now need to but have no idea how to bring in each char and apply a random symbol to each of the letters of the input. 我已将列表创建到一个名为var的obfuscate = ["!", "%", "*", "#", "@"] ,现在需要但不知道如何引入每个字符并应用一个输入的每个字母的随机符号。

original = input("Enter a 4-letter word:  ")

    letters = isolate_letters(original) 
    obsfucate_letters(letters) 
    obfuscated = recompose_obfuscated_letters(letters)

    print("Original:  ", original)
    print("Obfuscated:  ", obfuscated)

def isolate_letters(original):

    characters = list(original.lower())
    print (characters)
    return characters


def obsfucate_letters(original):

    import random
    obfuscate = ["!", "%", "*", "#", "@"]
    print (random.choice(obfuscate))

EDIT: 编辑:

def obfuscate_letters(word):

    import random
    new_word = ''
    for char in word:
        if random.random() < 0.9:
            new_word += random.choice(['!', '%', '&', '#', '@'])
        else:
            new_word += char
    letters = new_word
    print (letters)

def recompose_obfuscated_letters(letters):

        obfuscated = ''.join(letters)
        return obfuscated

These are my last two functions, i cannot get the letters variable returned: 这是我的最后两个函数,我无法获取返回的letters变量:

this is the respons to dddd: 这是对dddd的响应:

!@%!
Original: dddd 
Obfuscated: dddd

The top line of garble is what i need to go next to the Obfuscated bit ;/ 乱码的最上面一行是我需要在混淆部分旁边去的内容; /

You could make a dictionary that can map the letter to its obfuscated character 您可以制作一个字典,将字母映射到混淆的字符

import random
def encode(word, symbols):
    obfuscate = list(symbols)
    random.shuffle(obfuscate)
    d = dict(zip(word, obfuscate))
    return ''.join(d[i] for i in word)

>>> obfuscate = ["!", "%", "*", "#", "@"]
>>> word = 'test'
>>> encode(word, obfuscate)
'#%*#'

In the encode function, the third line creates a dictionary of the following form 在编码函数中,第三行创建以下形式的字典

{'s': '*',
 't': '#',
 'e': '%'}

Since I am shuffling the list before zip ing it, the map will be randomly paired. 由于我在zip列表之前先对列表进行混洗,因此地图将随机配对。 See the following few test calls 请参阅以下几个测试电话

>>> encode(word, obfuscate)
'%!#%'
>>> encode(word, obfuscate)
'@#%@'
>>> encode(word, obfuscate)
'@#*@'
>>> encode(word, obfuscate)
'%!*%'
>>> encode(word, obfuscate)
'@*%@'

If you don't need to recreate the word latter. 如果您不需要重新创建后者。 Here's a one line solution. 这是一线解决方案。

import random
def obfuscate(word):
    return ''.join([random.choice(["!", "%", "*", "#", "@"]) for char in word])

Explantion: 外植体:

[... for ... in ...] is a list comprehension , it generates a list of random characters using the random.choice(), then the ''.join() , concatenate all the generated characters in a single string. [... for ... in ...]是一个列表解析,它使用random.choice()生成一个随机字符列表,然后使用``.join()将所有生成的字符连接到一个字符中串。


EDIT: 编辑:

what if the 'word' was a user input (a four letter word)? 如果“单词”是用户输入(四个字母的单词)怎么办?

user_input = raw_input("Enter a 4-letter word:  ")
if len(user_input) == 4:
    print obfuscate(user_input)

is there a way that there is a 10% chance of a letter in the word being left alone and not being changed? 有没有一种方法可以使单词中的字母有10%的机会被单独保留而不被更改?

For this the list comprehension won't work (as far as I know), but you can still do it in a for loop. 为此,列表理解将不起作用(据我所知),但是您仍然可以在for循环中进行操作。

def obsfucate(word):
    new_word = ''
    for char in word:
        if random.random() > 0.1:
            new_word += random.choice(["!", "%", "*", "#", "@"])
        else:
            new_word += char
    return new_word

output: 输出:

Enter a 4-letter word:  Damn
D%*#

EDIT2: 编辑2:

Actually you can use list comprehensions! 实际上,您可以使用列表推导!

def obsfucate(word):
    return ''.join([random.choice(["!", "%", "*", "#", "@"]) if random.random() > 0.1 else char for char in word])

But for me it gets a little messy. 但是对我来说有点混乱。


EDIT 3: 编辑3:

Full code should be something like: 完整的代码应类似于:

import random

def obfuscate(word):
    new_word = ''
    for char in word:
        if random.random() > 0.1:
            new_word += random.choice(["!", "%", "*", "#", "@"])
        else:
            new_word += char
    return new_word

user_input = raw_input("Enter a 4-letter word:  ")
if len(user_input) == 4:
    print "Original:", user_input
    print "Obfuscate:", obfuscate(user_input)

Output: 输出:

Enter a 4-letter word:  Damn
Original: Damn
Obfuscate: D@m%

If you want to use you code as it is: 如果您想按原样使用代码:

import random

def isolate_letters(original):
    characters = list(original.lower())
    return characters

def obsfucate(word):
    return [random.choice(["!", "%", "*", "#", "@"]) if random.random() > 0.1 else char for char in word]

def recompose_obfuscated_letters(letters):
    obfuscated = ''.join(letters)
    return obfuscated

original = input("Enter a 4-letter word:  ")

letters = isolate_letters(original)
obsfucate_letters = obsfucate(letters)
obfuscated = recompose_obfuscated_letters(obsfucate_letters)

print("Original:", original)
print("Obfuscated:", obfuscated)

Output: 输出:

Enter a 4-letter word:  Damn
Original: Damn
Obfuscated: d!!%

This is my whole code, that you can use as is in your code excerpt. 这是我的整个代码,您可以在代码摘录中按原样使用。

from __future__ import print_function

def isolate_letters(s):
    return [c for c in s]

def obfuscate_letters(loc):
    from random import shuffle
    funny = ['!', '%', '*', '#', '@']
    # shuffle the list of funny characters
    shuffle(funny)
    # create a dictionary
    d = {c:f for f,c in zip(funny,set(loc))}
    # change in place the list of characters
    for i, c in enumerate(loc):
        loc[i] = d[c]

def recompose_obfuscated_letters(looc):
    return "".join(looc)

# here it is a copy and past from your OP (except for the spellung of obfuscate...)
original = 'funk'
letters = isolate_letters(original)
obfuscate_letters(letters)
obfuscated = recompose_obfuscated_letters(letters)

print('Original:    "%s"' % original)
print('Obfuscated:  "%s"' % obfuscated)

the output I have is 我的输出是

Original:    "funk"
Obfuscated:  "*#%@"

Key is using the shuffle function from the random module. 关键是使用random模块中的random shuffle功能。 shuffle changes at random the positions of the items in a list, so that when I access the terms in funny sequentially, I in effect access them at random... shuffle更改列表中项目的位置,以便当我按funny顺序访问术语时,实际上实际上是随机访问它们...

Next issue, I find the unique characters in the input word using set() and then construct a mapping, from real characters to funny characters. 下一期,我使用set()在输入单词中找到唯一字符,然后构造从真实字符到有趣字符的映射。

The last step is, of course, go through the original list and changing all its items one by one using the mapping that we have defined two lines above. 当然,最后一步是遍历原始列表,并使用我们在上面定义的两行映射来逐一更改其所有项目。

(this last part, modifying in place the original list, follows from how the OP coded her/his example) (最后一部分修改了原始列表,遵循OP如何编码她/他的示例)

A new answer because the OP has, substantially, a new question 一个新的答案,因为OP实质上有一个新问题

def obfuscate_letters(s,funny=[c for c in "!!!%%%&&&###@@@  "]):
    from random import shuffle
    shuffle(funny)
    for i, c in enumerate(s):
        s[i] = funny[i] if funny[i] != ' ' else s[i]

(yes, the default argument is mutable and changes at each invocation) (是的,默认参数是可变的,并且在每次调用时都会更改)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM