好吧,我快速回答了你的问题。我将解释我是如何完成这项任务的。也可能有更好的方法。据我从你的问题中了解到的是:
您主要关心的是保持单词长度为 15,并且保持
他们截然不同。
下面的代码片段正是这样做的。我首先读取文件anyFile.txt
其中应包含仅具有 15 个或更多字母的所有单词。我从你的问题假设你已经创建了这种文件。我将此文件的内容保存到english_words
.
然后我声明了一个charList = ['a','b','c','d','e','f']
。那么在我的代码中我只是使用这些6
用于创建不同单词的字母。如果您愿意,可以使用更多。越多越好。
然后我使用 for 循环遍历每个单词。在循环中,我首先删除单词以使其长度最多为 15 个字母。然后我打电话给我的checker()
做重的事情。
The checker()
将首先检查该单词是否已存在于oldWordList
如果是,那么它将生成一个新的不同单词。我使用递归来仔细检查新创建的单词是否不同。如果该词不在oldWordList
然后我只需将其附加到newWorldList
.
This newWorldList
最后将包含所有不同的单词。
不同的单词是如何生成的?
嗯,代码很简单。首先,我将字符串单词转换为列表tempList = list(item)
,以便我可以修改它。然后这里tempList[randomIndex] = charList[randomChar]
我正在选择一个随机字母charList = ['a','b','c','d','e','f']
然后将其分配到随机位置tempList
.
代码片段:请参阅:代码片段快速而肮脏,请随意进一步改进。
import random
fo = open("anyFile.txt","wb")
english_words = set(w.lower() for w in open('distinct_words_only.txt').read().split())
for item in english_words:
if len(item) > 15:
fo.write(item+'\n')
fo.close()
def checker(item):
randomIndex = random.randrange(0,15)#Random number to decide which position in word
randomChar = random.randrange(0,6)#Random number to pick a letter from charList
if item in oldWordList:
print 'Yes %s is present already'%item
tempList = list(item)#Convert string to list
tempList[randomIndex] = charList[randomChar]#Generate random word
item = "".join(tempList)#Covert list back to string
checker(item)#Recursion to double check
print 'Newly created word %s'%item
else:
print '%s is distinct'%item
newWordList.append(item)
english_words = set(w.lower() for w in open('anyFile.txt').read().split())
charList = ['a','b','c','d','e','f']
oldWordList = []
newWordList = []
for item in english_words:
item = item[0:15]
print 'Append item to oldWordList %s '%item
checker(item)
oldWordList.append(item)
print oldWordList#Will contain the original 15 letters words
print newWordList#Will contain distinct 15 letteres words
测试代码:创建一个名为的文件'distinct_words_only.txt'
写入以下内容并执行脚本代码:
averybigblackdogwithdots
averysmallwhitecatwithatail
averytinygreymousewithanose
averytinygreymousewithabignose
averybigblackdogwithdots
averybigblackdogwithdotts
averysmallwhitecatwithalongtail
averytinygreymousewithanosee
aaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaabbbbb
当脚本执行时你会看到print newWordList
将在控制台中向您显示长度为 15 个字母的不同单词列表。
局限性:我只是想指出,使用像我所做的那样的替换方法创建不同的单词也存在限制。例如:考虑一个由 2 个字母组成的单词,如果允许您使用 2 个字母来创建所有可能的单词,那么您只能生成 4 个不同的单词。
Eg:Word = IN,替换字母为 A、B
不同的词只能是:IA、IB、AN、BN。因为在替换方法中我们只能替换一个字母而不改变它们的位置。我们只能用A或B替换I或N。我们不能使用替换方法来做NA、NB、AI、BI等。
我希望这有点帮助。