首页 > 解决方案 > 我正在尝试制作一个单词生成器来生成不存在的单词

问题描述

问题是,当我使用此代码时,它会生成一个全新的单词,直到该单词中包含元音,而不是使用它已经生成的单词。如果它只是更改已经生成的单词中的一个字母而不是生成另一个字母,我会喜欢它。

import random as r

num1 = input("How many letters does each word need to contain? ")
num2 = input("How many lines do you want to add? ")
letter = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", 
"s", "t", "u", "v", "w", "x", "y", "z"]

def start_gen(length, lines):
generated_words = open("generated_words.txt", "a")
generated_words.write(f"{length} letters per word" + f" and {lines} lines")
generated_words.write("\n")
generated_words.write("\n")
r_words = 0
valid_word = False
line = 0
on = True
while on:
    word = ""
    for i in range(0, int(length)):
        word += letter[r.randint(0, 25)]
    print(word)
    generated_words.write(word)
    generated_words.write(" ")
    if "a" in word or "i" in word or "e" in word or "o" in word or "u" in word or "y" in word:
        print(word)
        valid_word = True
    # else:
    #   word[r.randint(0, num1)] = "a"
    if valid_word:
        r_words += 1
        print(f"{r_words} Valid Words")
        valid_word = False

    if r_words == 1:
        generated_words.write("\n")
        generated_words.write("\n")
        line += 1
        print(f"{line} Lines")
        r_words = 0
    if line == lines:
        generated_words.write("----------------------------------STOP-------------------------------- 
 --")
        generated_words.write("\n")
        generated_words.close()
        print("All done")
        break


start_gen(int(num1), int(num2))

输出:

每个单词 7 个字母和 4 行

njyjfko 
viliiuj 
bkfacce 
tqkgshk ywmzgbk 

标签: pythongenerator

解决方案


我仍然不太清楚你在期待什么,但我会将它解释为当你有一个没有元音的单词时,你想用元音替换现有的辅音。这意味着单行最多可以包含两个单词 - 一个没有元音,一个有元音替换到随机位置。如果保证第二个单词有元音并且没有元音是您拒绝某个单词的唯一原因,那么一行中最多应该有两个单词。

我提供了很多关于使代码更具可读性的建议,您可以根据需要选择合并这些建议。

import random 
#use original module name which is already short
#single letter variables are ok if their usage is localized to one part of a script, like within one loop
#but if they are used all over the script, then descriptive (but still concise) names are better.
#An exception is if a library is pervasively used everywhere in the script like numpy or pandas
#those have conventional two letter names np and pd

from string import asciilowercase
vowels = set('aeiouy')

#move prompts to after functions are defined

#don't to type your own list of letters, can use string.asciilowercase

def start_gen(word_length, num_lines):
    #made arguments more descriptive
    #i.e length of what? - length of the word
    #number of lines - not the collection of lines itself

    #changed file handle name to out_file
    #generated_words as a variable name sounds like a list or set
    with open("generated_words.txt", "a") as out_file:
        out_file.write(f"{word_length} letters per word and {num_lines} lines\n\n")

        #too many flags that do very similar things:r_words, valid_word
        #since you know number of lines, do a for loop on that number
        for _ in range(num_lines):
            #can use random.choice to just pick a letter instead of worrying about indices. 
            #can do it in a list comprehension one-liner
            first_word=''.join([random.choice(asciilowercase) for _ in range(word_length)])
            out_file.write(first_word)
            #check if has vowels by intersection with vowel set
            if len(set(first_word)&vowels)==0:
                #no vowels
                vowel = random.choice(list(vowels))
                position = random.randint(0,word_length-1)
                second_word = first_word[:position]+vowel+first_word[position+1:]
                out_file.write(' ' +second_word+'\n\n')
            else:
                 # has vowels
                 out_file.write('\n\n')
        out_file.write("----------------------------------STOP-------------------------------- 
 --\n")
        
         

if __name__ == '__main__':
    #this check prevents the prompts from happening if this script is imported
    #Prompts will only happen if script is run directly.
    num1 = input("How many letters does each word need to contain?\n > ")
    num2 = input("How many lines do you want to add?\n > ")
    start_gen(int(num1), int(num2))

推荐阅读