簡體   English   中英

拼字游戲作弊:在Python中將通配符評分為零

[英]Scrabble cheater: scoring wildcard characters to zero in Python

我是python世界的新手,我編寫了一個帶有兩個通配符(*和?)的scrabble finder代碼。 在給單詞評分時,我想將通配符的字母評分為零,但似乎不起作用。 我想知道這里缺少什么。

當您查看“#將分數和有效單詞添加到空列表”之后的行時,如果該單詞中的字母不在機架中,我嘗試編碼,我刪除了該字母,以便僅對其他不是來自通配符,並且與機架中的字母匹配。 例如,如果我的架子上有B *且單詞是BO,我想刪除O並僅給B評分,以便我可以將通配符評分為零。

但是結果卻不是我所期望的。

import sys

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 = []

# Call each word in the sowpods.txt
for word in data:
    # Change word to lowercase not to fail due to case.
    word_low = word.lower()
    candidate = True
    rack_letters = list(rack_low)
    # Iterate each letter in the word and check if the letter is in the
    # Scrabble rack. If used once in the rack, remove the letter from the rack.
    # If there's no letter in the rack, skip the letter.
    for letter in word_low:
        if letter in rack_letters:
            rack_letters.remove(letter)
        elif '*' in rack_letters:
            rack_letters.remove('*')
        elif '?' in rack_letters:
            rack_letters.remove('?')
        else:
            candidate = False
    if candidate == True:
        # Add score and valid word to the empty list 
        total = 0
        for letter in word_low:
            if letter not in rack_letters:
                word_strip = word_low.strip(letter)
                for letter in word_strip:
                    total += scores[letter]

        valid_words.append([total, word_low])

當總分時,您使用的是單詞列表中的單詞,而不是輸入的單詞:

total=0
for letter in word_low:
    ...

相反,這應該是:

total=0
for letter in rack_low:
    ...

同樣,您也不需要循環並刪除帶結尾的字母。 您可以擁有:

total = 0
for letter in rack_low:
    if letter not in rack_letters:
        try:
            total += scores[letter]
        except KeyError: # If letter is * or ? then a KeyError occurs
            pass

valid_words.append([total, word_low])

我的回答將略有不同,希望可以加快整個過程。 我們將從標准庫中導入另一個函數(置換),然后通過根據機架的長度(或傳遞的任何參數)修整總可能的單詞列表,找到可能的結果。

我已經對此發表了評論。

import sys
from itertools import permutations # So we can get our permutations from all the letters.

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.
txt_path = r'C:\\\\\sowpods.txt'
with open(txt_path,'r') as infile:
    raw_input = infile.readlines()
    # Added .lower() here.
    data = [i.strip('\n').lower() for i in raw_input]

## Sample rack of 7 letters with wildcard character.
sample_rack = 'jrnyoj?'

# Remove any non-alphabetic characters (i.e. - wildcards)
# We're using the isalpha() method.
clean_rack = ''.join([i for i in sample_rack if i.isalpha()])

# Trim word list to the letter count in the rack.
# (You can skip this part, but it might make producing results a little quicker.)
trimmed_data = [i for i in data if len(i) <= len(clean_rack)]


# Create all permutations from the letters in the rack
# We'll iterate over a count from 2 to the length of the rack
# so that we get all relevant permutations.
all_permutations = list()
for i in range(2, len(clean_rack) + 1):
    all_permutations.extend(list(map(''.join, permutations(clean_rack, i))))


# We'll use set().intersection() to help speed the discovery process.
valid_words = list(set(all_permutations).intersection(set(trimmed_data)))


# Print sorted list of results to check.
print(f'Valid words for a rack containing letters \'{sample_rack}\' are:\n\t* ' + '\n\t* '.join(sorted(valid_words)))

我們的輸出如下:

Valid words for a rack containing letters 'jrnyoj?' are:
    * jo
    * jor
    * joy
    * no
    * nor
    * noy
    * ny
    * on
    * ony
    * or
    * oy
    * yo
    * yon

如果要驗證結果是否確實在sowpods.txt文件中,則只需按要查找的單詞的索引位置對sowpods.txt列表進行索引:

trimmed_data[trimmed_data.index('jor')]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM