简体   繁体   English

备用换行符? 蟒蛇

[英]Alternate newline character? python

I am looking for a way to represent '\\n' with only one character. 我正在寻找一种仅用一个字符表示'\\ n'的方法。 I am writing a program that uses dictionaries to 'encrypt' text. 我正在编写一个使用字典“加密”文本的程序。 Because each character is represented in the dictionary, i am having a problem when my program gets to a '\\n' in a string, but reads it as '\\' 'n' . 因为每个字符都在字典中表示,所以我的程序在字符串中到达“ \\ n”但将其读取为“ \\”“ n”时遇到了问题。 Is there alternate way to represent a newline, that is only one character? 是否有替代方法来表示换行符(仅一个字符)? This is my code below, sorry if some of the indentation is messed up. 这是我的下面代码,如果某些缩进被弄乱了,抱歉。 I dont entirely understand how to input code into this window. 我不完全了解如何在此窗口中输入代码。 :) :)

##################################
#This program will take an input and encrypt it or decrypt it
#A cipher is used to transform the text, which can either be
#input or from a text file.
#The cipher can be any letter a-z, as well as most commonly used special characters
#numbers and spaces are not allowed.
#For the text, a-z, most special characters, space, and new line may be used.
#no numbers can be encrypted.
##################################

#These three dictionaries are used during the encryption process.
keyDict={'a': 17,'b': 3,'c':16,'d':26,'e':6,'f':19,'g':10,'h':12,
         'i':22,'j':8,'k': 11,'l':2,'m':18,'n':9,'o':23,'p':7,
         'q':5,'r': 20,'s': 1,'t': 24,'u':13,'v':25,'w':21,'x':15,
         'y':4,'z': 14, ' ':42, '.':0,'!': 27, '@': 34, '#': 35, '%': 37,
         '$': 36, "'": 33,'&': 39, '*': 40, ',': 29, '.': 30, '~': 41, ';': 31,
         ':': 32, '?': 28, '^': 38}

refDict2={' ': 43,  'a': 1, 'c': 3, 'b': 2, 'e': 5, 'd': 4, 'g': 7, 'f': 6, 'i': 9,
         'h': 8, 'k': 11, 'j': 10, 'm': 13, 'l': 12, 'o': 15, 'n': 14, 'q': 17,'\n': 42,
         'p': 16, 's': 19, 'r': 18, 'u': 21, 't': 20, 'w': 23, 'v': 22, 'y': 25,
         'x': 24, 'z': 26, ' ':0, '!': 27, '@': 34, '#': 35, '%': 37, '$': 36, "'": 33,
          '&': 39, '*': 40, ',': 29, '.': 30, '~': 41, ';': 31, ':': 32, '?': 28, '^': 38}

refDict={0: ' ', 1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e', 6: 'f', 7: 'g', 8: 'h', 9: 'i',
         10: 'j', 11: 'k', 12: 'l', 13: 'm', 14: 'n', 15: 'o', 16: 'p', 17: 'q', 42:'\n',
         18: 'r', 19: 's', 20: 't', 21: 'u', 22: 'v', 23: 'w', 24: 'x', 25: 'y', 26: 'z', 43:' ',
         32: ':', 33: "'", 34: '@', 35: '#', 36: '$', 37: '%', 38: '^', 39: '&', 40: '*',
         41: '~', 27: '!', 28: '?', 29: ',', 30: '.', 31: ';'}


#switch1 reverses a list. It is its own inverse, so we don't need an unswitch function. 
def switch1(l):
    return l[::-1]



#switch2 takes a list as input and moves every fourth entry to the front
#so switch2([a,b,c,d,e,f,g]) returns ([a,e,b,c,d,f,g])
#unswitch2 undoes this, so unswitch2([a,e,c,d,f,g]) returns [a,b,c,d,e,f,g]

def switch2(l):
    List4 = []
    ListNot4 = []
    for i in range(0,len(l)):
        if i%4 == 0:
            List4.append(l[i])
        else:
            ListNot4.append(l[i])
    return List4+ListNot4

def unswitch2(l):
    num4 = len(l)/4 + 1
    fixedList = l[num4:]
    for i in range (0,num4):
        fixedList.insert(4*i,l[i])
    return fixedList



#switch3 takes a list as input and returns a list with the first half moved to the end.
#so switch3([a,b,c,d,e,f]) returns [d,e,f,a,b,c]
#for lists of odd length, switch3 puts the separation closer to the beginning of the list, so the
#middle entry becomes the first entry.
#For example, switch3([a,b,c,d,e,f,g]) returns [d,e,f,g,a,b,c]

def switch3(l):
    return l[len(l)/2:] + l[:len(l)/2]

def unswitch3(l):
    if len(l)%2==0:
        return switch3(l)
    else:
        return l[len(l)/2+1:] + l[:len(l)/2+1]




##################################
#This is the Crypt function.
##################################
def Crypt(text, cipher):
    counter=0
    text=text.lower()
    cipher=cipher.lower()
    keyValue=[]
    textValue=[]
    newValue=[]
    newString=''
    for letter in cipher:
        keyValue.append(keyDict[letter])

    for letter in text:
        textValue.append(refDict2[letter])

    for num in textValue:
        newValue.append(num+keyValue[counter%len(keyValue)])
        counter+=1

    newValue = switch1(newValue)
    newValue = switch2(newValue)
    newValue = switch3(newValue)

    for num in newValue:
        newString+=refDict[num%43]

    return newString

##################################
#This is the Decrypt function
##################################
def Decrypt(encryptedText, cipher):
    counter=0
    cipher=cipher.lower()
    keyValue=[]
    textValue=[]
    finalValue=[]
    finalString=''

    for letter in encryptedText:
        textValue.append(refDict2[letter])

    textValue = unswitch3(textValue)
    textValue = unswitch2(textValue)
    textValue = switch1(textValue)

    for letter in cipher:
        keyValue.append(keyDict[letter])

    for num in textValue:
        finalValue.append((num-keyValue[counter%len(keyValue)])%43)
        counter+=1


    for num in finalValue:
        finalString+=refDict[num]

    return finalString


##################################
#This is the user interface.
##################################

choice=raw_input('Would you like to: 1)Encrypt or 2)Decrypt?  Pick 1 or 2: ')

if choice=='1':
    textType=raw_input("Would you like to: 1)encrypt a text file or 2) input the text to be encrypted? Pick 1 or 2: ")

    if textType=='1':
        cryptName=raw_input( 'Please enter the name of the text file you would like to encrypt(eg. text.txt): ')
        newName=raw_input('Please name the file in which the encrypted text will be stored(eg. secret.txt):' )
        cipher=raw_input("Now enter your personal encryption key(eg. secret code):" )

        cryptFile=open(cryptName, 'r')
        newFile=open(newName, 'w')
        print >> newFile, Crypt(cryptFile.read(),cipher)
        cryptFile.close()
        newFile.close()
        print "Ok, all done!"
    elif textType=='2':
        inputText=raw_input('Ok, please input the text you would like to encrypt(eg. computers rock!): ')
        cipher=raw_input("Now enter your personal encryption key (eg. ultra secret code): ")
        if inputText=='': print 'Oops, no text was entered! Try again!'
        else:
            print Crypt(inputText, cipher)
    else:
        print 'Try again!'

elif choice=='2':
    textType=raw_input("Would you like to:1)decrypt a text file or 2) input the text to be decrypted? Pick 1 or 2: ")
    if textType=='1':
        decryptName=raw_input( 'Please enter the name of the text file you would like to decrypt(eg. text.txt): ')
        newName2=raw_input('Please name the file in which the decrypted text will be stored(eg. secret.txt):' )
        cipher=raw_input("Now enter the encryption key that was used to encrypt the file(eg. secret code):" )
        #Text decrypt
        decryptFile=open(decryptName, 'r')
        newFile2=open(newName2, 'w')
        print>> newFile2, Decrypt(decryptFile.read(),cipher)
        #other stuff
        #textTodecrypt=decryptFile.read()
        #newFile2.writelines(Decrypt(textTodecrypt, cipher))


        decryptFile.close()
        newFile2.close()
        print "Ok, all done!"

    elif textType=='2':
        inputText=raw_input('Ok, please input the text you would like to decrypt(eg. dig&ak:do): ')
        cipher=raw_input("Now enter the encryption key that was used to encrypt the text (eg. ultra secret code): ")
        if inputText=='': print 'Oops, no text was entered! Try again!'
        else:
            print Decrypt(inputText, cipher)

print "Have a nice day!"


#there is an issue with the newline character 

'\\n' is one character. '\\ n'是一个字符。 It is a new line escape character and is just a representation of the new line. 它是换行符,只是换行符的表示。

please rephrase your question in a readable way. 请以可读的方式重新表达您的问题。

[Edit] I think I know what your problem is. [编辑]我想我知道您的问题是什么。 I ran your program and it is working just fine. 我运行了您的程序,它运行正常。 You are probably trying to pass '\\n' to your program from the command line. 您可能正在尝试从命令行将“ \\ n”传递给程序。 That will not work! 那不管用!

You see, if you gave raw_input() this string: line1\\nline2 it will escape the \\n and make it \\\\n like this: 'line1\\\\nline2' 您会看到,如果给raw_input()这个字符串: line1\\nline2 ,它将转义\\n并将其变成\\\\n例如: 'line1\\\\nline2'

So a quick hacky fix is to find and replace '\\\\n' with '\\n': 因此,一种快速的修正方法是找到“ \\\\ n”并将其替换为“ \\ n”:

text.replace('\\n', '\n')

I don't like this. 我不喜欢这样 But it will work for you. 但是它将为您工作。

A much better way is to read multiple lines, like this: 更好的方法是读取多行,如下所示:

input = raw_input('Please type in something: ')
lines = [input]
while input:
    input = raw_input()
    lines.append(input)

text = '\n'.join(lines)

print text

I'm guessing that your real problem is not with reading in \\n as a '\\' 'n' -- internally, Python should automagically translate \\n into a single character. 我猜测您的真正问题不是将\\ n读为'\\''n'-在内部,Python应该自动将\\ n转换为单个字符。

My guess is that the real problem is that your newlines are probably actually two characters -- carriage return ('\\r') and newline ('\\n'). 我的猜测是,真正的问题是换行符实际上可能是两个字符-回车符('\\ r')和换行符('\\ n')。 Try handling \\r in addition to \\n, and I wonder if that won't make your problem go away. 除\\ n外,还尝试处理\\ r,我想知道这是否不会解决您的问题。

I assume the problem is if there is \\n in the text to be decrypted, it breaks: 我认为问题是如果要解密的文本中有\\ n,它会中断:

KeyError: \

module body   in untitled at line 166
function Crypt    in untitled at line 94

Basically, raw_input() returns a string containing two characters \\ and n - and you have no mapping for \\ thus the error. 基本上, raw_input()返回一个包含两个字符\\n的字符串,并且您没有\\映射,因此会出现错误。

The simplest solution is so simply replace the literal characters \\n with the \\n escape sequence 最简单的解决方案是用\\n转义序列替换文字字符\\n

def Crypt(text, cipher):
    text.replace(r"\n", "\n")
    ... 

The raw string r"\\n" creates a string containing the literal character \\ followed by n (the same as doing "\\\\n" ). 原始字符串r"\\n"创建一个包含文字字符\\后跟n的字符串(与执行"\\\\n" )。

In a regular string "\\n" it's treated as the escape-sequence for a new-line. 在常规字符串"\\n"其视为换行符的转义序列。 So the above code-block replaces \\n in text with an newline. 因此,以上代码块用换行符替换了文本中的\\n

You may have to define a mapping for "\\n" in your keyDict mapping. 您可能必须在keyDict映射中为“ \\ n”定义一个映射。

Another solution would be to split the text using text.split(r"\\n") and treat each line separately. 另一个解决方案是使用text.split(r"\\n")分割文本,并分别处理每一行。 Or as others have suggested, use ord() every character and deal with numbers, rather than making your own numerical mapping. 或者像其他人所建议的那样,对每个字符使用ord()并处理数字,而不是进行自己的数字映射。

ord(c) Given a string of length one, return an integer representing the Unicode code point of the character when the argument is a unicode object, or the value of the byte when the argument is an 8-bit string. ord(c)给定一个长度为1的字符串,如果参数是unicode对象,则返回一个整数,该整数表示字符的Unicode代码点;如果参数是8位字符串,则返回一个字节的值。 For example, ord('a') returns the integer 97, ord(u'\†') returns 8224. This is the inverse of chr() for 8-bit strings and of unichr() for unicode objects. 例如, ord('a')返回整数97, ord(u'\†')返回8224。这是8位字符串的chr()和unicode对象的unichr()的逆。

As the docs explains, chr() is the opposite, and will turn the number back into a ASCII or Unicode character: 正如文档所解释的, chr()是相反的,它将把数字转换回ASCII或Unicode字符:

chr(i) Return a string of one character whose ASCII code is the integer i. chr(i)返回一个字符的字符串,其ASCII码为整数i。 For example, chr(97) returns the string 'a'. 例如, chr(97)返回字符串'a'。 This is the inverse of ord() . 这是ord()的逆函数。 The argument must be in the range [0..255], inclusive; 参数必须在[0..255]范围内(含); ValueError will be raised if i is outside that range. 如果我超出该范围,将引发ValueError。

Basically you would do.. 基本上你会的..

def Crypt(text, cipher):
    keyvalue = [ord(x) for x in cipher)
    textvalue = [ord(x) for x in text]

..instead of the two for loops (the list-comprehension is basically the same as making a list, looping over each character in text or cipher, and appending to the list each time) ..而不是两个for循环( 列表理解基本上与创建列表相同,循环遍历文本或密码中的每个字符,并每次附加到列表中)

Newline character is a single character. 换行符是单个字符。

>>> a = '\n'
>>> print len(a)
1
>>> a = '\n\n\n'
>>> a[1]
'\n'
>>> len(a)
3
>>> len(a[0])
1

So you misunderstand what your problem is. 因此,您会误解您的问题所在。

I'm new to Python, but there could be a way to simplify what you are doing by using the ord and chr functions to change characters to ASCII values and vice versa. 我是Python的新手,但是可以使用ordchr函数将字符更改为ASCII值,反之亦然,从而可以简化您的工作。 Here's a link to the built-in function documentation in Python . 这是Python内置函数文档的链接。

您可能应该利用数字的数值来执行加密,并避免那些大数据结构无论如何都将对非ascii文本失败。

A simple and fast way to replace the usual escapes with the corresponding ASCII characters is using the str.decode method: str.decode方法用相应的ASCII字符替换常用的转义符的简单,快速的方法是:

>>> s = r'This string has\tsome\nescapes'
>>> s
'This string has\\tsome\\nescapes'
>>> s.decode('string-escape')
'This string has\tsome\nescapes'
>>> print s
This string has\tsome\nescapes
>>> print s.decode('string-escape')
This string has some
escapes

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

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