python - 如何将未知次数的字符串拆分为列表
问题描述
在摩尔斯电码中:空格“”写成斜杠“/”。字母之间的间隙写成空格“”。
我做了一个英语到莫尔斯语的翻译器。这很容易,因为每个字母都是 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的新手,所以如果你能快速解释一下某些东西是如何/为什么起作用的,那就太好了:)
解决方案
您需要内置.split()
方法。
它做这种事情。
>>> '1/2/3'.split('/')
['1', '2', '3']
在这里阅读它。https://docs.python.org/3/library/stdtypes.html#string-methods
推荐阅读
- python - 在 cron 作业期间在 subshell 中引用 Python 3.7.3
- python - 无效的网址。姜戈
- c# - .net core 3 控制器中的并发/任务问题
- javascript - 未能加载资源 signalr.js.map 信号器核心
- javascript - 如何处理与图形渲染相关的 Dash (Plotly) Javascript 错误?
- grafana - 查询特定数据点的 Graphite Metrics
- r - 在 R 中获取新变量的问题
- css - ion-col 上的列之间没有填充?
- javascript - 给定未编码字符串的长度,有什么单一公式可以揭示 base-64 编码后该字符串的长度?
- python - Django Black 在 Pipenv 环境中未正确安装