Reputation: 35
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.
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
Upvotes: 3
Views: 881
Reputation: 419
What you need is to use the argparse
module
https://docs.python.org/3/library/argparse.html
I took your example and added argparse. There are some issues with your Scrabble constructor. But you will get the idea of using args on the command line
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)
Upvotes: 1
Reputation: 12675
You can get the arguments you script was passed on the command line with sys.argv
.
from sys import argv
print("This is a list of all of the command line arguments: ", argv)
Upvotes: 0