3

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
print("""
    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:
        i=i.split(",")
        lst.append(i)
print(lst)

word = random.choice(lst)
theWord = word

jumble = ""
while(len(word)>0):
    position = random.randrange(len(word))
    jumble+=word[position]
    word=word[:position]+word[position+1:]
print("The jumble word is: {}".format(jumble))

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

#congratulate the player
if(guess==theWord):
    print("Congratulations! You guessed it")
else:
    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!

4 Answers 4

7

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())

print(the_list)
  • 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

result:

['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)

print(the_list)

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)
Sign up to request clarification or add additional context in comments.

3 Comments

the one-liner did the trick! Thanks for the detailed answer and explanation.
@JureŠtabuc and Jean-François Fabre♦, is there a way to split for either '.' or '?' such that sentences ending in question mark also are split
yes, using regular expression split, like in my other answer: stackoverflow.com/a/52302595/6451573
1

use

lst.extend(i)

instead of

lst.append(i)

split return a list and you append a list to list everytime. Using extend instead will solve your problem.

Comments

1

Please try the following code:

import random

#Welcome the player
print("""
    Welcome to Word Jumble.
        Unscramble the letters to make a word.
""")

name = "   My name   "

filename = "words/amazement_words.txt"

lst = []
file = open(filename, 'r')
data = file.readlines()

another_lst = []
for line in data:
    lst.append(line.strip().split(','))
print(lst)
for line in lst:
    for li in line:
        another_lst.append(li.strip())

print()
print()
print(another_lst)

word = random.choice(lst)
theWord = word

jumble = ""
while(len(word)>0):
    position = random.randrange(len(word))
    jumble+=word[position]
    word=word[:position]+word[position+1:]
print("The jumble word is: {}".format(jumble))

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

#congratulate the player
if(guess==theWord):
    print("Congratulations! You guessed it")
else:
    print ("Sorry, wrong guess.")

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

Comments

0

str.split() generates a list, so if you append it to your result you get a list of lists. A solution would be to concatenate the 2 list (+)

You can get rid of the '\r\n' by stripping i before splitting it

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.