[英]Simple word scrabble code using python that takes command line parameters
I am trying to create a simple word scrabble script that finds words score values. 我正在尝试创建一个简单的单词拼字游戏脚本,找到单词得分值。 The script should reads two parameters from the command line and display the best word value, which returns the word with highest point value.
脚本应从命令行读取两个参数并显示最佳字值,该值返回具有最高点值的字。 I have created a constructor that reads the file and populate a dictionary of letter/value for use with the remaining methods of the class.
我创建了一个构造函数,它读取文件并填充字母/值的字典,以便与该类的其余方法一起使用。 For example the command line parameters should look like the following:
例如,命令行参数应如下所示:
scrabble.py c:\tiles.txt apple,squash
Output: The best value is squash with 18.
Here is what I have so far. 这是我到目前为止所拥有的。 I know that import argv is helful, but not sure how to get started.
我知道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
What you need is to use the
argparse
module
https://docs.python.org/3/library/argparse.html
你需要的是使用
argparse
模块
https://docs.python.org/3/library/argparse.html
I took your example and added argparse.
我举了你的例子并添加了argparse。
There are some issues with your Scrabble constructor. Scrabble构造函数存在一些问题。 But you will get the idea of using args on the command line
但是你会得到在命令行上使用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)
You can get the arguments you script was passed on the command line with sys.argv
. 您可以使用
sys.argv
获取脚本在命令行上传递的参数。
from sys import argv
print("This is a list of all of the command line arguments: ", argv)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.