【问题标题】:Simple word scrabble code using python that takes command line parameters使用带有命令行参数的python的简单单词拼字游戏代码
【发布时间】:2016-04-22 15:43:16
【问题描述】:

我正在尝试创建一个简单的单词拼字游戏脚本来查找单词得分值。该脚本应该从命令行读取两个参数并显示最佳单词值,它返回具有最高点值的单词。我创建了一个构造函数,它读取文件并填充一个字母/值字典,以用于该类的其余方法。例如,命令行参数应如下所示:

scrabble.py c:\tiles.txt apple,squash  
Output: The best value is squash with 18. 

这是我目前所拥有的。我知道 import argv 很有帮助,但不知道如何开始。

from sys import argv

class Scrabble:
    def __init__(self, tilesFile):
        with open(tilesFile, "r") as f:
            lines = [ line.strip().split(":") for line in f ]

        self.tiles = { k:int(v) for k,v in lines }

    def getWordValue(self, word):
        sum = 0
        for letter in word.upper():
            sum += self.tiles[letter]

        return sum

    def getBestWord(self):
        pass


def main():
    s1 = Scrabble("tile_values.txt")
    value = s1.getWordValue("hello")
    print(value)


if __name__ == '__main__':
   main()
   pass

【问题讨论】:

  • 是什么让您无法做到这一点?
  • 感谢您的回复。我不知道如何使用命令行参数的输入,而不是使用 python input--- value = s1.getWordValue("hello")
  • 您不确定如何使用输入,或不确定如何获取输入?
  • 不确定如何使用命令行参数的输入
  • 你可以初始化一个Scabble对象,然后在输入参数上调用getWordValue()方法。

标签: python python-3.x


【解决方案1】:

你需要的是使用argparse 模块 https://docs.python.org/3/library/argparse.html

我拿了你的例子并添加了 argparse。您的 Scrabble 构造函数存在一些问题。但是你会得到在命令行上使用 args 的想法

python scrabble.py tiles.txt apple squash orange

import argparse
import sys

class Scrabble:
    def __init__(self, tilesFile):
        with open(tilesFile, "r") as f:
            lines = [ line.strip().split(":") for line in f ]

        self.tiles = { k:int(v) for k,v in lines }

    def getWordValue(self, word):
        sum = 0
        for letter in word.upper():
            sum += self.tiles[letter]

        return sum

    def getBestWord(self):
        pass


def main(argv):
    s1 = Scrabble(argv[1])
    if len(argv) < 3:
        print 'no words given'
        sys.exit(1) 

    # argv[2:] means the items in argv starting from the 3rd item.
    # the first item will be the name of the script you are running
    # the second item should be the tiles file. 
    for word in argv[2:]:
        value = s1.getWordValue(word)
        print(value)


if __name__ == '__main__':
   main(argv)

【讨论】:

  • 感谢您的帮助。我是学生,我的教授希望我们从 sys.import 导入 argv。无论如何,你可以帮我吗?
  • 看一看。请记住在您的代码中添加一些好的错误检查。
【解决方案2】:

您可以使用sys.argv 获取您的脚本在命令行上传递的参数。

from sys import argv
print("This is a list of all of the command line arguments: ", argv)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多