如何将字符串拆分为单个字符?

2024-04-29 02:13:45 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我在做这个挑战:

问题:

It's 1868 and you've just bought a telegraph key so you can transmit messages in Morse code directly to your friend using a personal telegraph line. We've given you a file morsecode.txt which translates from any character (except a space) to its code. When a message is written in Morse code, characters are separated by spaces, while actual spaces are written as slash (/) in coded messages.

我想将输入字符串拆分为单个字符,并使用文件中的代码进行验证

我的代码:

data = {}
with open('morsecode.txt') as f:
  for line in f:
    key, value = line.split()
    data[key] = (value)
  
code = input('Message: ').lower() 

所需输出: desired output

由于某些原因,我无法在stackoverflow中共享文本文件

以下是文件中的文本:

A.-

B-

C-。-

D-

E

F.-

G--

H

J.--

K-。-

L.-

M--

N-

O--

p.-

Q——。-

R.-

S

T-

U.…-

V…-

W.--

X-…-

Y-。——

Z--

0---

1.--

2.——

3…——

4….-

5

6-

7--

8---

9--

.-.-.-.-

,------

  • -

/-…-

:--

”——

  • -

)——。————

-.-

(-)

=-…-

@.-


Tags: tokeyintxtyoumorselineve
2条回答

#首先定义词典

`

dic={...} # as your list above
tmp=''
for a in input():
    tmp=tmp+"".join(dic.get(a)) 
print(tmp)

`

假设从文本文件读取时data字典正在更新,则可以执行以下操作:

code = input('Message: ').lower()
new_string = ' '.join(data[letter] for letter in code) 

.join将iterable作为参数。您可以从字典中获取特定值并将其传递到join

相关问题 更多 >