Home > Net >  How to generate all possible words in a text file
How to generate all possible words in a text file

Time:06-06

I want to generate all possible words from a text file but my code is not correct.

My existing code:

file = open('../data.txt')
for line in file.readlines():
    line = line.strip()

    for line1 in file.readlines():
        line1 = line1.strip()      
        print ("{} {}".format(line, line1))

data.txt #-- my data file in text format

hero
muffin
ego
abundant
reply
forward
furnish

Needed Output: #-- generated result

hero muffin
hero ego
hero abundant
hero reply
hero forward
hero furnish

muffin hero
muffin ego
muffin abundant
muffin reply
muffin forward
muffine furnish

ego hero
ego muffin
so on...

CodePudding user response:

Trying to read from the same file handle multiple times in a nested loop isn't going to work because you'll hit the end of the file the first time through your inner loop, and although you could make it work by closing and reopening the file inside the outer loop, there's no reason to do that (it's both overly complicated and needlessly slow).

Instead, just read all the words into a list (once, so you're not wasting time re-reading the same information from disk over and over) and use itertools.permutations to generate all the 2-word permutations of that list.

import itertools

with open("data.txt") as f:
    words = [word.strip() for word in f]

for p in itertools.permutations(words, 2):
    print(*p)

prints:

hero muffin
hero ego
hero abundant
hero reply
hero forward
hero furnish
muffin hero
muffin ego
muffin abundant
...
  • Related