首页 > 解决方案 > 如何将未知次数的字符串拆分为列表

问题描述

在摩尔斯电码中:空格“”写成斜杠“/”。字母之间的间隙写成空格“”。

我做了一个英语到莫尔斯语的翻译器。这很容易,因为每个字母都是 1 个字符长,所以我可以将它分成字符。然而,走另一条路是困难的。我需要能够检测字母之间的拆分,但还要确保我没有检测到单词之间的拆分。

这是我的python代码:

print("\nNote: not all characters are logged. \n\n")

english = [ "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","1","2","3","4","5","6",
            "7","8","9","0",".",",",";",":","!","?","(",")","-","_","!","&",
            "=","+","$","/","'"," "]

morse = [ ".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",
          ".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",
          ".--","-..-","-.--","--..",".----","..---","...--","....-",".....",
          "-....","--...","---..","----.","-----",".-.-.-","-..-","-.-.-.",
          "---...","--..--","..--..","-.--.","-.--.-","-....-","..--.-","--..--",
          ".-...","-...-",".-.-.","...-..-","-..-.",".----."," /"]





while True:
    print ("English to Morse: press 1 ")
    print ("Morse to English: press 2 ")
    print ("What is morse code: press 3")
    translate_direction = input("\n>").replace(" ","")

                            
    if translate_direction == "1":
    
        tobetranslated = input("\nTranslate English to Morse Code\n\n> ").lower()
        splitupinput = list(tobetranslated)
        finishedoutput = ""

        for i in splitupinput:
            englishloc = english.index(i)
            finishedoutput = finishedoutput + morse[englishloc]
            finishedoutput = finishedoutput + " "    
              
        print(finishedoutput)

    elif translate_direction == "2":

        tobetranslated = input("\nTranslate Morse Code to English\n\n> ").lower()
        tobetranslated = tobetranslated.replace(" ","ß ")
        
        finishedoutput = ""

        for i in splitupinput:
            englishloc = english.index(i)
            finishedoutput = finishedoutput + morse[englishloc]
            finishedoutput = finishedoutput + " "    
              
        print(finishedoutput)

    elif translated_irection == "3":
        print("Morse code is... (insert long-winded explanation of the history of morse code and its applications)")

.replace()用一些不在摩尔斯电码中的字符加上空格来替换空格,这样当我沿着“π”分割时,它会丢失,我有一个空格,这样我就可以确定单词之间的分割。

但是,我有一个问题:我不知道如何将一个字符串沿着无法确定的拆分数量拆分成一个列表。

有什么帮助吗?

有趣的事实:我只有标准库。对不起!我是未成年人,无论我要求多少,我的父母都不愿意下载任何东西。

我也是python的新手,所以如果你能快速解释一下某些东西是如何/为什么起作用的,那就太好了:)

标签: python

解决方案


您需要内置.split()方法。

它做这种事情。

>>> '1/2/3'.split('/')
['1', '2', '3']

在这里阅读它。https://docs.python.org/3/library/stdtypes.html#string-methods


推荐阅读