在Python中将整数字符串转换为整数

时间:2015-04-28 23:49:26

标签: python error-handling binary integer

我正在尝试在python中编写一个程序,通过首先将输入单词转换为Morse来编码项目,然后将点和短划线更改为将被视为二进制数字等的1和0。 这是一段代码:

def mimary_encode(input):
if input.find('!')!=-1 or input.find('@')!=-1 or input.find('#')!=-1 or input.find('$')!=-1 or input.find('%')!=-1 or input.find('^')!=-1 or input.find('&')!=-1 or input.find('*')!=-1 or input.find('(')!=-1 or input.find(')')!=-1 or input.find('_')!=-1 or input.find('-')!=-1 or input.find('=')!=-1 or input.find('+')!=-1 or input.find('.')!=-1 or input.find('"')!=-1 or input.find("'")!=-1 or input.find(',')!=-1 or input.find(' ')!=-1 or input.find(';')!=-1 or input.find(':')!=-1 or input.find('[')!=-1 or input.find(']')!=-1 or input.find('{')!=-1 or input.find('}')!=-1 or input.find('?')!=-1 or input.find('<')!=-1 or input.find('>')!=-1:
    print "Inputs cannot contain spaces or symbols"
else:base=input
nol=len(input)
if base.find("a")!=-1:
    base=base.replace("a",".-")
if base.find("b")!=-1:
    base=base.replace("a","-...")
if base.find("c")!=-1:
    base=base.replace("c","-.-.")
if base.find("d")!=-1:
    base=base.replace("d","-..")
if base.find("e")!=-1:
    base=base.replace("e",".")
if base.find("f")!=-1:
    base=base.replace("f","..-.")
if base.find("g")!=-1:
    base=base.replace("g","--.")
if base.find("h")!=-1:
    base=base.replace("h","....")
if base.find("i")!=-1:
    base=base.replace("i","..")
if base.find("j")!=-1:
    base=base.replace("j",".---")
if base.find("k")!=-1:
    base=base.replace("k","-.-")
if base.find("l")!=-1:
    base=base.replace("l",".-..")
if base.find("m")!=-1:
    base=base.replace("m","--")
if base.find("n")!=-1:
    base=base.replace("n","-.")
if base.find("o")!=-1:
    base=base.replace("o","---")
if base.find("p")!=-1:
    base=base.replace("p",".--.")
if base.find("q")!=-1:
    base=base.replace("q","--.-")
if base.find("r")!=-1:
    base=base.replace("r",".-.")
if base.find("s")!=-1:
    base=base.replace("s","...")
if base.find("t")!=-1:
    base=base.replace("t","-")
if base.find("u")!=-1:
    base=base.replace("u","..-")
if base.find("v")!=-1:
    base=base.replace("v","...-")
if base.find("w")!=-1:
    base=base.replace("w",".--")
if base.find("x")!=-1:
    base=base.replace("x","-..-")
if base.find("y")!=-1:
    base=base.replace("y","-.--")
if base.find("z")!=-1:
    base=base.replace("z","--..")
if base.find("1")!=-1:
    base=base.replace("1",".----")
if base.find("2")!=-1:
    base=base.replace("2","..---")
if base.find("3")!=-1:
    base=base.replace("3","...--")
if base.find("4")!=-1:
    base=base.replace("4","....-")
if base.find("5")!=-1:
    base=base.replace("5",".....")
if base.find("6")!=-1:
    base=base.replace("6","-....")
if base.find("7")!=-1:
    base=base.replace("7","--...")
if base.find("8")!=-1:
    base=base.replace("8","---..")
if base.find("9")!=-1:
    base=base.replace("9","----.")
if base.find("0")!=-1:
    base=base.replace("0","-----")
if base.find("-")!=-1:
    base=base.replace("-","0")
if base.find(".")!=-1:
    base=base.replace(".","1")
int(base)


mimary_encode("hi")

我知道这可能不是编写它的最好方法,但问题是python一直给我的错误是:

Traceback (most recent call last):
  File "C:/Documents and Settings/Moshe's Programming/Desktop/Python       
Projects/Mimary/Mimary attempt 1.py", line 86, in <module>
    mimary_encode("hi")
  File "C:/Documents and Settings/Moshe's Programming/Desktop/Python         
Projects/Mimary/Mimary attempt 1.py", line 83, in mimary_encode
print base + 1
TypeError: cannot concatenate 'str' and 'int' objects

这个错误是什么意思?我该如何解决这个错误?我已经把base变成了一个整数 - 不是吗?

2 个答案:

答案 0 :(得分:1)

Although your code is reaaally messed up, it works. However, your first error was raised due to the line int("base").

If you write int("base") you are trying to turn the string "base" into an integer, which is something impossible to do.

Then, you changed the code to print base + 1 which is also impossible to do, once base is a string and you can't sum strings and integers with + sign. So, what you want to do is:

def mimary_encode(base): 
    #Dowhateveryouwant
    return int(base) #Only if you are sure base contains only integers
print mimary_encode("hi")

答案 1 :(得分:0)

The error is coming from print base + 1, where base is a string and 1 an integer.

Here is an alternative implementation of your function. First, I define the morse code encoding as a dictionary. In the function, I first convert all letters to lower case. I then use the get dictionary function to return the morse code value if it is in the dictionary, otherwise it uses an empty string to filter it. This differs from the original approach where bad data is filtered. Here, I'm only looking for data that is in my dictionary. Finally, I join together the encoded letters using a generator: code = " ".join((morse.get(c, "") for c in input_string)) which is similar to list comprehension but more efficient for large strings.

from string import letters

msg = 'I hear 13 knights from the Round Table are here!!!'

def mimary_encode(input_string):
    input_string = ''.join([c.lower() if c in letters else c
                            for c in input_string])
    code = " ".join((morse.get(c, "") for c in input_string))
    return code

morse = {
 '0': '-----',
 '1': '.----',
 '2': '..---',
 '3': '...--',
 '4': '....-',
 '5': '.....',
 '6': '-....',
 '7': '--...',
 '8': '---..',
 '9': '----.',
 'a': '.-',
 'b': '-...',
 'c': '-.-.',
 'd': '-..',
 'e': '.',
 'f': '..-.',
 'g': '--.',
 'h': '....',
 'i': '..',
 'j': '.---',
 'k': '-.-',
 'l': '.-..',
 'm': '--',
 'n': '-.',
 'o': '---',
 'p': '.--.',
 'q': '--.-',
 'r': '.-.',
 's': '...',
 't': '-',
 'u': '..-',
 'v': '...-',
 'w': '.--',
 'x': '-..-',
 'y': '-.--',
 'z': '--..'}

To encode the message (defined earlier as msg):

>>> mimary_encode(msg)
'.. .... . .- .-. .---- ...-- -.- -. .. --. .... - ... ..-. .-. --- -- - .... . .-. --- ..- -. -.. - .- -... .-.. . .- .-. . .... . .-. .'

Given the one-to-one mapping of your dictionary, you can reverse it using a dictionary comprehension:

reverse_morse = {v: k for k, v in morse.iteritems()}

You can then reverse the morse code to convert it back into an alpha/numeric string.

>>> ''.join([reverse_morse.get(c, "") for c in mimary_encode(msg).split(" ")])
'ihear13knightsfromtheroundtablearehere'

Notice that all letters are converted to lower case and that the exclamations have been removed.