gpt4 book ai didi

python - 设置长度的python中的契约(Contract)词

转载 作者:太空狗 更新时间:2023-10-30 00:08:50 28 4
gpt4 key购买 nike

我目前正在尝试制作一种“单词混合器”:对于两个给定的单词和指定的所需长度,程序应返回这两个单词的“混合”。然而,它可以是任何类型的混合:它可以是第一个单词的前半部分与第二个单词的后半部分相结合,它可以是随机混合,任何东西。

例子:

鱼+蛋糕,长度5:fiske

狗 + 猫,长度 4:doga

后期+交叉,长度6:losste

我写了一个非常草率的代码(如下所示),我很感激关于我做错了什么的一些提示(因为我的输出不是很好)以及是否有任何可以改进的地方。

from random import randint

name1 = "domingues"
name2 = "signorelli"
names = [name1,name2]
# a list of the desired lengths
lengths = [5,6,7]
mixes = []

def sizes(size):
if size == 5:
letters1 = randint(2,3)
else:
letters1 = randint(2,size-2)
letters2 = size-letters1
return letters1, letters2

def mix(letters1, letters2):
n = randint(0,1)
if n == 1:
a = 0
else:
a = 1
n1 = names[n]
n2 = names[a]
result = n1[0:letters2]+n2[-letters1::]
return result

file = open("results.txt","w+")
for leng in lengths:
file.write("RESULTS WITH "+str(leng)+" LETTERS \n")
file.write("\n")
for i in range(10):
let1, let2 = sizes(leng)
result = mix(let1,let2)
while result == name1 or result == name2:
result = mix(let2)
if result not in mixes:
mixes.append(result)
for m in mixes:
if m not in file:
file.write(m+" \n")
file.write("\n")
file.close()

(顺便说一句,感谢您花时间帮助我,非常感谢!)

最佳答案

一般来说,这是与人工智能相关的问题,因为我们隐含地想要获得可读的混合词。我只是编写了简单(而且很脏)的代码,试图从训练数据中捕获元音和辅音的序列,并根据捕获的规则构建混合词。

import random

consonants_pat = 'BCDFGHJKLMNPQRSTVXZ'.lower()
vowels_pat = 'aeiouy'

train_data = '''
This our sentence to be used as a training dataset
It should be longer
'''

def build_mixer(train_data, num=3, mixed_len=(2, 4)):

def _get_random_pattern(td, wlen):
td_splitted = td.lower().split()
while True:
w = random.choice(list(filter(lambda x: len(x)>=wlen, td_splitted)))
for j in range(len(w)-wlen):
yield tuple(map(lambda x: 0 if x in vowels_pat else 1, w[j:j + wlen]))

def _select_vowels(w):
return


def _mixer(w1, w2, num=num, mixed_len=mixed_len):
allowed_letters = w1.lower().strip() + w2.lower().strip()
ind = 1
for j in range(num):
wlen = random.choice(range(*mixed_len))
pattern = _get_random_pattern(train_data, wlen)
_aux = allowed_letters
word = ''
try:
for pat in pattern:
for k in pat:
if k == 0:
choiced = random.choice(list(filter(lambda x: x in vowels_pat, _aux)))
word += choiced
else:
choiced = random.choice(list(filter(lambda x: x in consonants_pat, _aux)))
word += choiced
l = list(_aux)
l.remove(choiced)
_aux = ''.join(l)
ind += 1
yield word
if ind>num:
raise StopIteration
except IndexError:
continue

return _mixer


mixer = build_mixer(train_data, num=6, mixed_len=(3,6))
for mixed in mixer('this', 'horse'):
print(mixed)

我得到了以下的话:

het hetihs hetihssro sheo hsio tohir

关于python - 设置长度的python中的契约(Contract)词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54977174/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com