搜索
首页后端开发Python教程解决 Word Cookie 谜题:Python 冒险

玩游戏是一种让大脑从一天的压力中放松下来的方式,或者只是从工作中休息一下。然而,有时,游戏本身就会带来压力,所以我认为“Word Cookies”就是这种情况,这是一款有趣的益智游戏,你会得到一组打乱的字母,并被要求解决其中包含的单词。

Solving Word Cookies Puzzles: A Python Adventure

随着我在游戏中的进展,解决问题变得越来越困难,几乎没有资源可以帮助我,我多次陷入困境。但是等一下,我用 Python 编写代码,为什么我找不到出路呢?这就是 Python 语言大放异彩的地方。

现在我如何使用Python来解决混乱的问题。我需要一种方法来检查乱序字母中的单词,我将实现分解为简单的步骤。

计划:

  1. 获取单词词典来检查打乱的字母。
  2. 创建一个仅包含 n 个字母单词的 csv,在本例中我创建了一个包含 3 个字母单词到 7 个字母单词的 csv
  3. 检查 csv 中的某个单词是否其所有字母都包含在打乱的字母中
  4. 将其保存到自己的单词数列表中,例如,如果一个单词是“age”,那么它将保存到 3 个字母的单词列表中,依此类推。
  5. 显示结果

让我们开始工作吧:

首先,我在网上搜索并找到了一本可以下载 csv 格式的字典,并将其分成包含每个字母的单独 CSV 文件。它看起来像这样:

Solving Word Cookies Puzzles: A Python Adventure

接下来,我有一个 python 代码来从 A-Z 检查 CSV,并挑选出 3 个字母的单词,并省略带有空格和其他不可用格式的单词。这是同时对 4、5、6 和 7 个字母的单词进行的。

它看起来像这样:

import os
import csv
import re
import pandas as pd

# Define folder paths
input_folder = 'C:\Users\Zenbook\Desktop\Word lists in csv'
output_folder = 'C:\Users\Zenbook\Desktop\Word list output'


# Function to find words of specific lengths in text
def find_words_of_length(text, length):
    words = re.findall(r'\b\w+\b', text)
    return [word for word in words if len(word) == length]


# Initialize dictionaries to store words of each length
words_by_length = {3: set(), 4: set(), 5: set(), 6: set(), 7: set()}

# Loop through all CSV files in the input folder
for filename in os.listdir(input_folder):
    if filename.endswith('.csv'):
        filepath = os.path.join(input_folder, filename)

        # Read each CSV file with a fallback encoding
        with open(filepath, 'r', encoding='ISO-8859-1') as file:
            reader = csv.reader(file)
            for row in reader:
                # Loop through each cell in the row
                for cell in row:
                    for length in words_by_length.keys():
                        words = find_words_of_length(cell, length)
                        words_by_length[length].update(words)

# Save words of each length to separate CSV files
for length, words in words_by_length.items():
    output_file = os.path.join(output_folder, f'{length}_letters.csv')
    with open(output_file, 'w', newline='', encoding='utf-8') as file:
        writer = csv.writer(file)
        for word in sorted(words):  # Sort words for neatness
            writer.writerow([word])

print("Words have been saved to separate CSV files based on their length.")


这是我指定的输出文件夹中的结果:

Solving Word Cookies Puzzles: A Python Adventure

现在有了这个输出文件夹,我只需检查其中的单词,看看它们是否包含在打乱的字母中。这是执行此操作的代码:

import csv

# Define the string to check against
check_string = 'langaur'

# Define the folder path for CSV files
input_folder = 'C:\Users\Zenbook\Desktop\Word list output'


# Function to check if all letters in word can be found in check_string
def is_word_in_string(word, check_string):
    # Check if each letter in the word is in the string
    for letter in word:
        if word.count(letter) > check_string.count(letter):
            return False
    return True


# Check words for 3, 4, 5, 6 and 7-letter CSVs
for length in [3, 4, 5, 6, 7]:
    input_file = f'{input_folder}/{length}_letters.csv'
    print(f"\nLength {length}:")

    with open(input_file, 'r', encoding='utf-8') as file:
        reader = csv.reader(file)
        found_words = []

        for row in reader:
            word = row[0].strip()  # Remove any extra whitespace
            if is_word_in_string(word, check_string):
                found_words.append(word)

        # Print all found words for the given length
        for i in found_words:
            print(i)

快速细分:

我们从前面的代码中获取输出文件夹,并将其用作上面实际解决方案代码中的输入文件夹。该解决方案的优点在于函数“is_word_in_string”的简单性。我们不必检查打乱的单词中是否包含单个字母,因为这将是为出现多次的字母编写的额外逻辑。

我们只需要检查字典单词中的每个字母是否小于或等于它在打乱单词中出现的次数,然后我们就可以确认字典单词的每个字母是否确实存在在打乱的信件中。

让我们看看代码的实际效果:

Solving Word Cookies Puzzles: A Python Adventure

万岁!现在,当我陷入困境时,我有办法继续前进。它不仅仅是总是欺骗系统,这没有什么乐趣,但是当我真正需要它时,这个解算器就会派上用场。我还可以获得尽可能多的额外单词,这样我就可以填满那个罐子并获得一些很棒的资源。

就是这样。 Python 是一种多功能语言,可以自动化快速完成任务。您可以简单地在日常活动中使用它,例如这样的,或者复杂的工作任务,甚至更高级的工作,例如机器学习。找到一个今天要处理的 python 项目。干杯。

嘿,我的名字是 Ifedolapo,我是一名前端开发人员和 Python 程序员(顺便说一下,我也进行设计)。您可以通过 Portfolio 网站了解更多关于我

感谢您阅读这篇文章。

以上是解决 Word Cookie 谜题:Python 冒险的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
列表和阵列之间的选择如何影响涉及大型数据集的Python应用程序的整体性能?列表和阵列之间的选择如何影响涉及大型数据集的Python应用程序的整体性能?May 03, 2025 am 12:11 AM

ForhandlinglargedatasetsinPython,useNumPyarraysforbetterperformance.1)NumPyarraysarememory-efficientandfasterfornumericaloperations.2)Avoidunnecessarytypeconversions.3)Leveragevectorizationforreducedtimecomplexity.4)Managememoryusagewithefficientdata

说明如何将内存分配给Python中的列表与数组。说明如何将内存分配给Python中的列表与数组。May 03, 2025 am 12:10 AM

Inpython,ListSusedynamicMemoryAllocationWithOver-Asalose,而alenumpyArraySallaySallocateFixedMemory.1)listssallocatemoremoremoremorythanneededinentientary上,respizeTized.2)numpyarsallaysallaysallocateAllocateAllocateAlcocateExactMemoryForements,OfferingPrediCtableSageButlessemageButlesseflextlessibility。

您如何在Python数组中指定元素的数据类型?您如何在Python数组中指定元素的数据类型?May 03, 2025 am 12:06 AM

Inpython,YouCansspecthedatatAtatatPeyFelemereModeRernSpant.1)Usenpynernrump.1)Usenpynyp.dloatp.dloatp.ploatm64,formor professisconsiscontrolatatypes。

什么是Numpy,为什么对于Python中的数值计算很重要?什么是Numpy,为什么对于Python中的数值计算很重要?May 03, 2025 am 12:03 AM

NumPyisessentialfornumericalcomputinginPythonduetoitsspeed,memoryefficiency,andcomprehensivemathematicalfunctions.1)It'sfastbecauseitperformsoperationsinC.2)NumPyarraysaremorememory-efficientthanPythonlists.3)Itoffersawiderangeofmathematicaloperation

讨论'连续内存分配”的概念及其对数组的重要性。讨论'连续内存分配”的概念及其对数组的重要性。May 03, 2025 am 12:01 AM

Contiguousmemoryallocationiscrucialforarraysbecauseitallowsforefficientandfastelementaccess.1)Itenablesconstanttimeaccess,O(1),duetodirectaddresscalculation.2)Itimprovescacheefficiencybyallowingmultipleelementfetchespercacheline.3)Itsimplifiesmemorym

您如何切成python列表?您如何切成python列表?May 02, 2025 am 12:14 AM

SlicingaPythonlistisdoneusingthesyntaxlist[start:stop:step].Here'showitworks:1)Startistheindexofthefirstelementtoinclude.2)Stopistheindexofthefirstelementtoexclude.3)Stepistheincrementbetweenelements.It'susefulforextractingportionsoflistsandcanuseneg

在Numpy阵列上可以执行哪些常见操作?在Numpy阵列上可以执行哪些常见操作?May 02, 2025 am 12:09 AM

numpyallowsforvariousoperationsonArrays:1)basicarithmeticlikeaddition,减法,乘法和division; 2)evationAperationssuchasmatrixmultiplication; 3)element-wiseOperations wiseOperationswithOutexpliitloops; 4)

Python的数据分析中如何使用阵列?Python的数据分析中如何使用阵列?May 02, 2025 am 12:09 AM

Arresinpython,尤其是Throughnumpyandpandas,weessentialFordataAnalysis,offeringSpeedAndeffied.1)NumpyArseNable efflaysenable efficefliceHandlingAtaSetSetSetSetSetSetSetSetSetSetSetsetSetSetSetSetsopplexoperationslikemovingaverages.2)

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

螳螂BT

螳螂BT

Mantis是一个易于部署的基于Web的缺陷跟踪工具,用于帮助产品缺陷跟踪。它需要PHP、MySQL和一个Web服务器。请查看我们的演示和托管服务。

VSCode Windows 64位 下载

VSCode Windows 64位 下载

微软推出的免费、功能强大的一款IDE编辑器

EditPlus 中文破解版

EditPlus 中文破解版

体积小,语法高亮,不支持代码提示功能

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)