当代码在python中拼写作弊者时添加通配符

时间:2019-02-16 01:04:20

标签: python python-3.x

我正在尝试将一个通配符(每个字符之一:一个*和一个?,总计最多两次)添加到我的拼字游戏机架中,该通配符可以更改为任何单个字符。如果输入bo?*,*和?应该是a〜z,并且所有可能的单词都需要与sowpods.txt中的单词进行比较。我应该如何编辑此代码? :)现在,我的代码可以不使用通配符了。预先感谢!

++当我打印结果时,它显示为(10,'bomb')。我如何使其像(10,炸弹)?删除或替换均无效。

import sys
import string

scores = {"a": 1, "c": 3, "b": 3, "e": 1, "d": 2, "g": 2,
          "f": 4, "i": 1, "h": 4, "k": 5, "j": 8, "m": 3,
          "l": 1, "o": 1, "n": 1, "q": 10, "p": 3, "s": 1,
          "r": 1, "u": 1, "t": 1, "w": 4, "v": 4, "y": 4,
          "x": 8, "z": 10}

# Get the Scrabble rack from the command line.
if len(sys.argv) < 2:
    print("no rack error.")
    exit(1)

rack = sys.argv[1]
rack_low = rack.lower()

# Turn the words in the sowpods.txt file into a Python list.
with open("sowpods.txt","r") as infile:
    raw_input = infile.readlines()
    data = [datum.strip('\n') for datum in raw_input]

# Find all of the valid sowpods words that can be made
# up of the letters in the rack.
valid_words = []

for word in data:
    word_low = word.lower()
    candidate = True
    rack_letters = list(rack_low)
    for letter in word_low:
        if letter not in rack_letters:
            candidate = False
            break # No need to keep checking letters.
        else:
            rack_letters.remove(letter)
    if candidate == True:
        # Get the Scrabble scores for each word.
        total = 0
        for letter in word_low:
            total = total + scores[letter]
        valid_words.append([total, word_low])

# Print the valid words, sorted by Scrabble score.

valid_words.sort(reverse = True)
for entry in valid_words:
    score = entry[0]
    word_low = entry[1]
    print((score, word_low))

print("Total number of words:", len(valid_words))

1 个答案:

答案 0 :(得分:0)

我将假定所有空白图块均由相同的字符“ *”表示。我不知道您为什么想要两个不同的解决方案,但是如果您愿意,可以适当修改我的解决方案。

用一个函数和一个较短的for循环替换for循环(保持其他所有不变):

def can_make_word(word):
    rack_letters = list(rack_low)
    for letter in word_low:
        if letter in rack_letters:
            rack_letters.remove(letter)
        elif '*' in rack_letters:
            rack_letters.remove('*') 
        else:
            return False
    return True

for word in data:
    word_low = word.lower()
    if can_make_word(word_low):
        # Get the Scrabble scores for each word.
        total = 0
        for letter in word_low:
            total = total + scores[letter]
        valid_words.append([total, word_low])

由于正在打印元组,因此打印输出中出现单引号。它们不是字符串中的字符,因此您无法删除它们。如果将打印语句重写为(删除一组括号)为:

print(score, word_low)

您将在输出中看到10, bomb,而不是(10, 'bomb')。这是因为当Python打印一个元组时,它通过调用其str()函数来格式化每个元素,该函数在单引号内显示​​字符串。您可以在IDLE上玩这个游戏,也可以在一个交互式Python会话中玩耍以了解它的工作原理。