我正在尝试创建一个简单的单词拼字游戏脚本,用于查找单词得分值。脚本应从命令行读取两个参数并显示最佳字值,该值返回具有最高点值的字。我创建了一个构造函数,它读取文件并填充字母/值的字典,以便与该类的其余方法一起使用。例如,命令行参数应如下所示:
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
答案 0 :(得分: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)
答案 1 :(得分:0)
您可以使用sys.argv
获取脚本在命令行上传递的参数。
from sys import argv
print("This is a list of all of the command line arguments: ", argv)