如果dict包含它,如何保留“空格”?

时间:2013-11-09 13:46:33

标签: python join dictionary append

我只是试图从文件加密中读取并显示它。

我希望逐字显示结果,但不知何故空格被移除(我的dict也包含'':''),结果文本显示没有空格。

例如,

aa bb cc 是我从文件中读取的内容,

当前输出ffggğğ,但我希望它为 ffggğğ

...请帮忙......

monocrypt = {
    'a': 'f',
    'b': 'g',
    'c': 'ğ',
    'ç': 'h',
    'd': 'ı',
    'e': 'i',
    'f': 'j',
    'g': 'k',
    'ğ': 'l',
    'h': 'm',
    'ı': 'n',
    'i': 'o',
    'j': 'ö',
    'k': 'p',
    'l': 'r',
    'm': 's',
    'n': 'ş',
    'o': 't',
    'ö': 'u',
    'p': 'ü',
    'r': 'v',
    's': 'y',
    'ş': 'z',
    't': 'a',
    'u': 'b',
    'ü': 'c',
    'v': 'ç',
    'y': 'd',
    'z': 'e',
    ' ': ' ',
}

inv_monocrypt = {}
for key, value in monocrypt.items():
    inv_monocrypt[value] = key

f = open("C:\\Hobbit.txt","r")
print("Reading file...")

message = f.read()
crypt = ''.join(i for i in message if i.isalnum())
encrypted_message = []
for letter in crypt:
    encrypted_message.append(monocrypt[letter.lower()])

print(''.join(encrypted_message))

3 个答案:

答案 0 :(得分:0)

你正在放弃这一步的所有空白

crypt = ''.join(i for i in message if i.isalnum())

所以把它们留在那里。使用带有默认参数的dict.get来保留不是键的字母

crypt = f.read()
encrypted_message = []
for letter in crypt:
    encrypted_message.append(monocrypt.get(letter.lower(), letter.lower()) )

如果你真的只想保留空格(而不是标点符号/其他空格等)

message = f.read()
crypt = ''.join(i for i in message if i.lower() in monocrypt)
encrypted_message = []
for letter in crypt:
    encrypted_message.append(monocrypt[letter.lower()])

你可以像这样简化

message = f.read().lower()
crypt = ''.join(i for i in message if i in monocrypt)
encrypted_message = [monocrypt[letter] for letter in crypt]

答案 1 :(得分:0)

不确定它是否按预期工作,因为我没有hobbit.txt,但我做了一个小的重写,使代码更简单一些。它也应该解决你的问题。

monocrypt = {
    'a': 'f',
    'b': 'g',
    'c': 'ğ',
    'ç': 'h',
    'd': 'ı',
    'e': 'i',
    'f': 'j',
    'g': 'k',
    'ğ': 'l',
    'h': 'm',
    'ı': 'n',
    'i': 'o',
    'j': 'ö',
    'k': 'p',
    'l': 'r',
    'm': 's',
    'n': 'ş',
    'o': 't',
    'ö': 'u',
    'p': 'ü',
    'r': 'v',
    's': 'y',
    'ş': 'z',
    't': 'a',
    'u': 'b',
    'ü': 'c',
    'v': 'ç',
    'y': 'd',
    'z': 'e',
    ' ': ' ',
}

with open("hobbit.txt") as hobbitfile:
    file_text = hobbitfile.read()

crypted_message = ""

for char in file_text:
    char = char.lower()
    if char in monocrypt:
        crypted_message += monocrypt[char]
    else:
        #I don't know if you want to add the other chars as well.
        #Uncomment the next line if you do.
        #crypted_message += str(char)
        pass

print(crypted_message)

答案 2 :(得分:0)

检查文档: http://docs.python.org/2/library/stdtypes.html#str.isalnum

isalnum会删除你的空白。

如果你想保留空格字符,请使用它,其他一切都保持不变:

crypt = ''.join(i for i in message if i.isalnum() or i==' ')

如果要保留所有空格,请执行以下操作:

crypt = ''.join(i for i in message if i.isalnum() or i.isspace())