Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to generate all possible words in a text file

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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...

>Solution :

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
...
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading