需要弄清楚为什么我的Python程序不起作用(排序-按字母顺序排列)

时间:2018-10-13 04:50:35

标签: python

该指令旨在:编写一个Python程序,该程序从命令行中读取两个或多个字符串,然后 按字母顺序显示它们。 基本要求 -验证输入 -正确的错误处理 -对作为程序参数传递的两个或多个单词进行排序 -正确的文件 -正确的文档说明文件顶部应 包含您的姓名,程序名称,目的 程序和该程序的示例调用。也 文档中复杂或混乱的代码行。 但是,其中不应有太多。

我的代码:

# mySorter.py. 
# This program reads two or more strings as program
# arguments and displays them sorted.
# Program will sort alphabetically the words from a string provided by the 
user
# Take input from the user
my_str = input("Enter a string: ")

# breakdown the string into a list of words
words = my_str.split()

# sort the list
words.sort()

for word in words:
print(word)

if len(my_str.split()) < 2:
print("Please provide more than one word.")

显然,我做错了。有人告诉我该程序不符合要求。它必须在程序启动时读取传递给程序的参数。有什么建议吗?谢谢。

2 个答案:

答案 0 :(得分:0)

# mySorter.py. 
# This program reads two or more strings as program
# arguments and displays them sorted.
# Program will sort alphabetically the words from a string provided by the user

# Simply run this program as follows:
# python your_script.py "hello user"

import argparse

argparser = argparse.ArgumentParser()
argparser.add_argument('my_str',help = 'User string')
args = argparser.parse_args()
if args.my_str:
    my_str = args.my_str

    # breakdown the string into a list of words
    words = my_str.split()

    if len(words) <= 1:
        print("Please provide more than one word.")
    else:
        # sort the list
        words.sort()

        for word in words:
            print(word)
else:
    print('No words to sort!')
    print('Try the following: python my_script.py "hello world"')

“启动程序时必须读取传递给程序的参数”的要求。对我来说,告诉我您需要使用argparser来发送字符串,而不会受到input()的提示。 这就解释了为什么您不满足它的原因,因为您目前没有这样做:-)

答案 1 :(得分:0)

  

有人告诉我该程序不符合要求。它必须在程序启动时读取传递给程序的参数

我认为他们希望您使用input()之类的东西来获取需要从命令行进行排序的输入字符串列表,而不是使用sys.argv来提示用户输入字符串。 python myscript.py str1 str2 str3

https://www.tutorialspoint.com/python/python_command_line_arguments.htm中的python3进行了少许修改,将以下内容放入“ test.py”文件中:

import sys

print('Number of arguments: {} arguments'.format(len(sys.argv)))
print('Argument List: {}'.format(sys.argv))

在命令行中,执行以下操作:

python test.py arg1 arg2 arg3

这将产生以下结果:

Number of arguments: 4 arguments.
Argument List: ['test.py', 'arg1', 'arg2', 'arg3']

要获取不包括脚本名称的参数,可以执行类似words = sys.argv[1:]的操作。这将从第二个参数开始返回参数列表。然后,您可以按照原始程序对列表进行排序。