简体   繁体   English

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

[英]Turning an integer string to an integer in Python

I am trying to write a program in python that codes items by first turning the input word to Morse and then changes the dots and dashes to ones and zeros which will be treated as binary numbers etc. This is a code snippet: 我试图用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")

I know this is probably not the best way to write it, but the problem is the error python keeps giving me is: 我知道这可能不是编写它的最佳方法,但是问题是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

What does this error mean? 这个错误是什么意思? How can I fix this error? 如何解决此错误? I already did turn base into an integer-didn't I? 我已经把基数变成整数了,不是吗?

Although your code is reaaally messed up, it works. 尽管您的代码被彻底搞砸了,但是它可以工作。 However, your first error was raised due to the line int("base") . 但是,由于行int("base")引发了您的第一个错误。

If you write int("base") you are trying to turn the string "base" into an integer, which is something impossible to do. 如果编写int("base") ,则试图将字符串“ base”转换为整数,这是不可能完成的。

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. 然后,您将代码更改为print base + 1 ,这也是不可能的,一旦base是一个string并且您不能用+号将字符串和整数相加。 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")

The error is coming from print base + 1 , where base is a string and 1 an integer. 错误来自print base + 1 ,其中base是一个字符串,1是一个整数。

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. 然后, get字典中存在莫尔斯电码值,则使用get dictionary函数返回它的莫尔斯电码值;否则,使用空字符串对其进行过滤。 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. 最后,我使用生成器将编码后的字母组合在一起: code = " ".join((morse.get(c, "") for c in input_string))与列表理解相似,但对大型字符串更有效。

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 ): 编码消息(之前定义为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. 请注意,所有字母都转换为小写,并且感叹号已被删除。

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

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