gpt4 book ai didi

python - 使用带有命令行参数的 python 的简单单词拼字游戏代码

转载 作者:行者123 更新时间:2023-11-28 18:31:29 28 4
gpt4 key购买 nike

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

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

最佳答案

您需要的是使用 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)

关于python - 使用带有命令行参数的 python 的简单单词拼字游戏代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36798144/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com