我有一个txt文件 scrabble_letters.txt ,内容如下:
1 E
1 A
1 I
1 N
1 O
... etc
我需要编写一个程序来帮助我对每个单词进行评分,从scrabble_letters.txt中读取每个单词的分数,如下所示:
Word: kiwi
11 points
以下是scrabble_letters.txt使用法语版拼字游戏中字母得分的分数的示例:
Word: kiwi
22 points
到目前为止,我能够编译一个粗略的程序(不能按预期运行),如下所示:
f = open('scrabble_letters.txt')
for line in f:
SCORES = (line.strip())
total = 0
def scrabble_score(word):
total = ()
Word = input("Word: ")
for letter in Word:
total += SCORES[letter]
print (total, "points")
我被困在这里,只是不确定如何从法语版的Scrabble创建输出或它是如何工作的。
答案 0 :(得分:4)
假设你有一个文件'scrabble_letters.txt',其中包含每个字母的分数,那么下面的代码定义了一个方法scrabble_score()
,它将一个单词作为参数并打印出该单词的分数。
f = open('scrabble_letters.txt')
scores = {}
# make a map of letter to its score. Important: note the type casting to integer.
for line in f:
temp = line.strip()
# line.split() takes a line eg. "1 K" and returns an array ['1', 'K'] i.e. splits by spaces.
temp = line.split()
scores[temp[1]] = int(temp[0])
def scrabble_score(word):
total = 0
for letter in word:
total += scores[letter]
print (total, "points")
对于示例文本文件:
1 E
1 A
1 I
1 N
1 O
5 K
6 W
将方法作为
运行scrabble_score('KIWI')
打印输出13 points
P.S:得分版(正如你在问题中提到的那样)完全取决于scrabble_letters.txt
的内容。您可以选择使用if-else
块