用Python创建多语言拼字游戏

2024-06-03 01:00:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个txt文件_字母.txt内容如下:

1 E  
1 A  
1 I  
1 N  
1 O  
... etc  

我需要编写一个程序来帮助我为每个单词打分,读入拼字游戏中每个字母的分数_字母.txt,如下所示:

^{pr2}$

下面是拼字游戏的一个例子_字母.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创建输出,或者它是如何工作的。在


Tags: 文件in程序txt内容for字母line
1条回答
网友
1楼 · 发布于 2024-06-03 01:00:22

假设你有一个文件拼字游戏_字母.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") 

对于示例文本文件:

^{pr2}$

将方法作为

scrabble_score('KIWI')

打印输出13 points

注:评分版本(正如你在问题中提到的法语)完全依赖于scrabble_letters.txt的内容。根据使用if-else块的条件,您可以选择打开所需的文件

相关问题 更多 >