如何保留“空格”尽管dict包含它?

2024-06-02 07:13:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我只是试图从一个文件中读取加密并显示它。你知道吗

我想逐字显示结果,但不知怎么的,空格被删除了(我的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))

Tags: 文件keyinmessageforvalueencrypted空格
3条回答

检查文档: 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())

我不确定它是否按预期工作,因为我没有霍比特人.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)

你在这一步删除了所有的空白

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]

相关问题 更多 >