Jure Štabuc Jure Štabuc - 2 months ago 30
Python Question

Create one list with strings using read text file in Python

I want to make a jumble game in python that uses words from a text file rather than from words written directly into the python file(in this case the code works perfectly). But when I want to import them, I get this list:

[['amazement', ' awe', ' bombshell', ' curiosity', ' incredulity', '\r\n'], ['godsend', ' marvel', ' portent', ' prodigy', ' revelation', '\r\n'], ['stupefaction', ' unforeseen', ' wonder', ' shock', ' rarity', '\r\n'], ['miracle', ' abruptness', ' astonishment\r\n']]

I want words to be sorted in one single list, for example:

["amazement", "awe", "bombshell"...]

This is my python code:

import random

#Welcome the player
Welcome to Word Jumble.
Unscramble the letters to make a word.

filename = "words/amazement_words.txt"

lst = []
with open(filename) as afile:
for i in afile:

word = random.choice(lst)
theWord = word

jumble = ""
position = random.randrange(len(word))
print("The jumble word is: {}".format(jumble))

#Getting player's guess
guess = input("Enter your guess: ")

#congratulate the player
print("Congratulations! You guessed it")
print ("Sorry, wrong guess.")

input("Thanks for playing. Press the enter key to exit.")

I have a text file with words:

amazement, awe, bombshell, curiosity, incredulity,
godsend, marvel, portent, prodigy, revelation,
stupefaction, unforeseen, wonder, shock, rarity,
miracle, abruptness, astonishment

Thank you for help and any suggestions!


quasi one-liner does it:

with open("list_of_words.txt") as f:
    the_list = sorted(word.strip(",") for line in f for word in line.split())

  • use a double for in a gen-comprehension
  • splitting against spaces is the trick: it gets rid of the line-termination chars and multiple spaces. Then, just get rid of the commas using strip().
  • Apply sorted on the resulting generator comprehension


['abruptness', 'amazement', 'astonishment', 'awe', 'bombshell', 'curiosity', 'godsend', 'incredulity', 'marvel', 'miracle', 'portent', 'prodigy', 'rarity', 'revelation', 'shock', 'stupefaction', 'unforeseen', 'wonder']

Only drawback of this quick method is that if 2 words are only separated by a comma, it will issue the 2 words as-is.

In that latter case, just add a for in the gencomp like this to perform a split according to comma and drop the empty result string (if word):

with open("list_of_words.txt") as f:
    the_list = sorted(word for line in f for word_commas in line.split() for word in word_commas.split(",") if word)


or in that latter case, maybe using regex split is better (we need to discard empty strings as well). Split expression being blank(s) or comma.

import re

with open("list_of_words.txt") as f:
    the_list = sorted(word for line in f for word in re.split(r"\s+|,",line) if word)