How to shuffle all letters of words within a file . txt

Asked

Viewed 112 times

0

I am creating a program that shuffles all the letters of the words inside a file . txt in which each line there is only one word.

Example of a . txt (which I called Wordlist.txt):

batata
limonada
áfrica

How I expect output to be:

atabat
adaoilmn
ficára

What I tried to do:

import random


with open('wordlist.txt', encoding='utf-8') as f:
    lines = f.readline()
    list = list(lines)
    random.shuffle(list)
    result = ''.join(list)
    print(result)

Output:

limonada
batata
áfrica

In my attempt, the program only scrambles the order in which words are presented.

My goal is that the order in which the words are presented stays the same, but with each word having its letters shuffled.

1 answer

2


There’s two little problems there:

You confused the "with" command with a "for": "with", although it requires a code block, the block runs only once. So only the first line is read, and the program ends.

By the result you described, you must be calling the .readlines() (with "s" at the end) of the file, and not the ". readline" that would read only the first line and would shuffle the first word.

With "readlines", a list is created in which each line of the file is an item,.

Another thing is that you’re calling your variable list. The language allows you to do this, but after you run the first time, the original call of list, which builds a list from a sequence, is over-written by its variable. You need to use another name for that variable.

So as the command with really is only needed in more complex programs, to prevent memory and resource leakage - and the for, if a file is passed already reads a file line by line, your program can look like this:

import random


for line in open('wordlist.txt', encoding='utf-8'):
    line = list(linha.strip())
    random.shuffle(line)
    result = ''.join(line)
    print(result)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.