0

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

而且我想逐字显示结果,但是以某种方式删除了空格(我的字典还包含'':'')并且结果文本显示时没有空格。

例如,

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

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

...请帮忙...

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))
4

3 回答 3

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]
于 2013-11-09T14:00:23.850 回答
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)
于 2013-11-09T14:06:18.847 回答
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())
于 2013-11-09T14:09:04.580 回答