我只是想知道如何在此特定程序中将sys.argv
列表用于命令行参数而不是输入方法。因为argc
在python中不存在,所以使用len
方法可以确定长度,对吧?
感谢您提前提供帮助!
MORSE_CODE_DICT = {
'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':'-----',
}
```python
def encryptor(text):
encrypted_text = ""
for letters in text:
if letters != " ":
encrypted_text = encrypted_text + MORSE_CODE_DICT.get(letters) + " "
else:
encrypted_text += " "
print(encrypted_text)
text_to_encrypt = input("Enter Some Text To Encrypt : ").upper()
encryptor(text_to_encrypt)
sys.argv
的第一个元素是执行程序的名称。其余的是传递给程序的参数,由外壳程序管理。例如,对于文件名扩展,*.txt
将针对找到的每个文本文件扩展为单独的元素。您可以编写测试程序以查看不同的扩展
test.py:
import sys
print(sys.argv)
两种运行方式是
$ python test.py hello there buckaroo
['test.py', 'hello', 'there', 'buckaroo']
$ python test.py "hello there buckaroo"
['test.py', 'hello there buckaroo']
对您来说,一个简单的解决方案是将参数连接起来,以便一个人可以输入带引号或不带引号的输入
import sys
text_to_encrypt = " ".join(sys.argv[1:]).upper()
encryptor(text_to_encrypt)
添加我们得到的代码
$ python morsecoder.py hello there buckaroo
.... . .-.. .-.. --- - .... . .-. . -... ..- -.-. -.- .- .-. --- ---
注意,我们不需要专门知道argv的长度。 Python喜欢迭代-通常这种情况是,如果您需要某些东西的长度,那么您做错了。