简体   繁体   English

如何在Python中制作单词的所有可能组合

[英]How to make all possible combinations of a word in Python

I have a txt file with all of the letters in the alphabet that looks like this: 我有一个txt文件,其中包含字母表中的所有字母,如下所示:

a 一种

b b

c C

etc.. 等等..

I also have a word list of words that is only 3 letters long: 我还有一个单词列表,单词列表只有3个字母长:

ago

age 年龄

bat 蝙蝠

bag

etc... 等等...

I want to create a list that prints out all of the combinations possible starting with the first word ago: 我想创建一个列表,从第一个单词开始打印出所有可能的组合:

My test program looks like this: 我的测试程序如下所示:

allcombi=[]
s= list("ago")
the.list=[]
with open("alfabeth.txt", "r", encoding = "utf-8") as letters:
    for line in letters:
        letter = line.strip()
        s[0]=letter
        print(s)

Now I only change the first letter, but I have a really hard time trying to join the letters because it only looks like this: 现在,我只更改第一个字母,但是我很难加入这些字母,因为它看起来像这样:

['a', 'g', 'o'] ['b', 'g', 'o'] .... ['a','g','o'] ['b','g','o'] ....

HELP WITH: 帮助:

  1. Print it out as ['ago','bgo'] instead 改为将其打印为['ago','bgo']

  2. Instead of just changing the first letter, change it one letter at a time in index 0,1 and 2 one letter at a time in the word. 与其仅更改第一个字母,不如一次将索引0,1和2中的每个字母更改为一个单词中的一个字母。 The output should be 27*3 rows long with ['ago','bgo',........,'agx',agy,'agz'] 输出应为27 * 3行,并带有['ago','bgo',........,'agx',agy,'agz']

I will later search for all of the items in my new list in a dictionary but that I can figure out myself it's just this part that really gotten me stuck. 稍后,我将在词典中搜索我的新列表中的所有项目,但我可以弄清楚自己是这部分真正让我陷入了困境。

This will generate a list of all combinations for a given word: 这将生成给定单词的所有组合的列表:

from string import ascii_lowercase
word = "ago"
combos = []
for i in xrange(len(word)):
    for l in ascii_lowercase:
        combos.append( word[:i]+l+word[i+1:] )

as @Farhan.K put in the comments, what you are looking for is a string method that creates a new string from an iterable: join 为把@ Farhan.K的意见,你正在寻找的是创建从迭代一个新字符串的字符串方法: join

Join is a method of a string where it joins an iterable containing strings with that original string in-between them. Join是字符串的一种方法,它将一个包含字符串的可迭代字符串与它们之间的原始字符串连接起来。 for example if you have a list of words that are to be a sentance, you can join them with a space separating each one by calling ' '.join(listOfWords) . 例如,如果您有一个待定的单词列表,则可以通过调用' '.join(listOfWords)来用空格分隔每个' '.join(listOfWords) In your case, you have a list of chars that need to be joined without any delimiter, so you pass an empty string as the separator: ''.join(listOfChars) 在您的情况下,您有一个需要连接的字符列表,没有任何定界符,因此您传递了一个空字符串作为分隔符: ''.join(listOfChars)

here with list comprehension 这里的列表理解

[b+'g'+e for b in alphabet for e in alphabet]

and you can define alphabet with another list comprehension 您可以使用另一个列表理解来定义字母

alphabet=[chr(c) for c in range(ord('a'),ord('z')+1)]

perhaps not much shorter than writing char by char... 也许不比一个字符一个字符地写...

You need nested loops for starters. 对于初学者,您需要嵌套循环。 When you get the grip of what you actually trying to do, then you can see the itertools package. 当您掌握了实际要做的事情后,便可以看到itertools软件包。

With the code that you have provided, you should need something like: 使用提供的代码,您应该需要类似以下内容的代码:

s = list('ago')
the_list=[]
with open("alfabeth.txt", "r", encoding = "utf-8") as letters:
    lines = [line for line in letters]

for i in range(len(s)):
    for ii in lines:
        tmp_s = list(s)
        tmp_s[i] = ii
        print(''.join(tmp_s))

And with itertools this becomes: 使用itertools,它变成:

from itertools import product

s = list('ago')
with open("alfabeth.txt", "r", encoding = "utf-8") as letters:
    lines = [line.strip() for line in letters]

for i in product(range(len(s)), lines):
    print(''.join(s[:i[0]] + [i[-1]] + s[i[0] + 1:]))

I figured it out! 我想到了! With a neat while loop too. 带有一个整齐的while循环。 So proud. 好骄傲 Posting answer here anyway. 无论如何在这里发布答案。

    allakombi=[]
s= list("söt")#startord
characters=[]
with open("alfabetet.txt", "r", encoding = "utf-8") as bokstäver:
        for rad in bokstäver:
               bokstav = rad.strip()
               characters.append(bokstav)

k=0
while k<3:
       i=0
       while i <len(characters):
              s= list("söt")
              s[k]=characters[i]
              i=i+1
              s="".join(s)
              allakombi.append(s)
       k=k+1


print(allakombi)

You need a few nested loops to get the combinations, as an example: 您需要一些嵌套循环来获取组合,例如:

from string import ascii_lowercase

words = ["ago"]
combs = []
for word in words:
    for i, letter in enumerate(word):
        for l in ascii_lowercase:
            tmp = list(word)
            tmp[i] = l
            combs.append("".join(tmp))

print combs



>>> ['ago', 'bgo', 'cgo', 'dgo', 'ego', 'fgo', 'ggo', 'hgo', 'igo', 'jgo', 'kgo', 'lgo', 'mgo', 'ngo', 'ogo', 'pgo', 'qgo', 'rgo', 'sgo', 'tgo', 'ugo', 'vgo', 'wgo', 'xgo', 'ygo', 'zgo', 'aao', 'abo', 'aco', 'ado', 'aeo', 'afo', 'ago', 'aho', 'aio', 'ajo', 'ako', 'alo', 'amo', 'ano', 'aoo', 'apo', 'aqo', 'aro', 'aso', 'ato', 'auo', 'avo', 'awo', 'axo', 'ayo', 'azo', 'aga', 'agb', 'agc', 'agd', 'age', 'agf', 'agg', 'agh', 'agi', 'agj', 'agk', 'agl', 'agm', 'agn', 'ago', 'agp', 'agq', 'agr', 'ags', 'agt', 'agu', 'agv', 'agw', 'agx', 'agy', 'agz']

You could try something like : 您可以尝试类似:

letter=["ago"]

from string import ascii_lowercase

for i in ascii_lowercase:
    print(i+letter[0][1:])
    print(letter[0][:1]+i+letter[0][2:])
    print(letter[0][:2]+i)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM