So for some background: I've been going through learning python the hard way and have taken a little break to try doing a few fun things, I came across on a suggestion on daniweb, to try create a program in which you enter in a list of characters and it will then print out any word that contain all those characters.
I've figured out how to do it manually, here's the below code:
string = raw_input("Please enter the scrable letters you have: ")
for line in open('/usr/share/dict/words', 'r').readlines():
if string[0] in line and string[1] in line and string[2] in line:
print line,
But I somehow cannot figure out how to get it to work by using loops (that way the user can enter in a list of characters of any length. I figured something like the below would work, but it doesn't appear to do so:
while i < len(string)-1:
if string[i] in line: tally = tally + 1
i = i + 1
if tally == len(string)-1: print line
else: i = 0
Any help in the right direction would be much appreciated, thanks.
I would use all with a comprehension for this ... and the comprehension is a loop
user_string = raw_input("Please enter the scrable letters you have: ")
for line in open('/usr/share/dict/words', 'r').readlines():
if all(c in line for c in user_string):
print line,
Set operations can come in handy here:
inp = set(raw_input("Please enter the scrable letters you have: "))
with open('/usr/share/dict/words', 'r') as words:
for word in words:
if inp <= set(word):
print word,
Related
Im very new on python, actually, Im not even a programer, Im a doctor :), and as a way to practice I decided to wright my hangman version.
After some research I couldnt find any way to use the module "random" to return a word with an especific length. As a solution, I wrote a routine in which it trys a random word till it found the right lenght. It worked for the game, but Im sure its a bad solution and of course it affects the performance. So, may someone give me a better solution? Thanks.
There is my code:
import random
def get_palavra():
palavras_testadas = 0
num_letras = int(input("Choose the number of letters: "))
while True:
try:
palavra = random.choice(open("wordlist.txt").read().split())
escolhida = palavra
teste = len(list(palavra))
if teste == num_letras:
return escolhida
else:
palavras_testadas += 1
if palavras_testadas == 100: # in large wordlists this number must be higher
print("Unfortunatly theres is no words with {} letters...".format(num_letras))
break
else:
continue
except ValueError:
pass
forca = get_palavra()
print(forca)
You may
read the file once and store the content
remove the newline \n char fom each line, because it count as a character
to avoid making choice on lines that hasn't the good length, filter first to keep the possible ones
if the good_len_lines list has no element you directly know you can stop, no need to do a hundred picks
else, pick a word in the good_length ones
def get_palavra():
with open("wordlist.txt") as fic: # 1.
lines = [line.rstrip() for line in fic.readlines()] # 2.
num_letras = int(input("Choose the number of letters: "))
good_len_lines = [line for line in lines if len(line) == num_letras] # 3.
if not good_len_lines: # 4.
print("Unfortunatly theres is no words with {} letters...".format(num_letras))
return None
return random.choice(good_len_lines) # 5.
Here is a working example:
def random_word(num_letras):
all_words = []
with open('wordlist.txt') as file:
lines = [ line for line in file.read().split('\n') if line ]
for line in lines:
all_words += [word for word in line.split() if word]
words = [ word for word in all_words if len(word) == num_letras ]
if words:
return random.choice(words)
When I guess the letter it keeps applying the letter. for example
say the word is words, then I would guess the letter d, then it would do
ddddd. it uses that letter for the whole word. here is my code.
import random
print(" Welcome to the HangMan game!!\n","You will have six guesses to get the answer correct, or you will loose!!!",)
lines = open("../WordsForGames.txt").read()
line = lines[0:]
#lines 24-28 Randomly generate a word from a text file
words = line.split()
myword = random.choice(words)
print(myword)
words = myword
fake = '_'*len(myword)
count = 0
print(fake)
guesses = 0
guess = input("Enter a letter you would like to guess: ")
fake = list(fake) #This will convert fake to a list, so that we can access and change it.
for re in range(0, len(myword)):#For statement to loop over the answer (not really over the answer, but the numerical index of the answer)
fake[re] = guess #change the fake to represent that, EACH TIME IT OCCURS
print(''.join(fake))
if guess != (''.join(fake)):
print("The letter ", guess,"was in the word. Guess another letter please!")
guess = input("Enter another letter you would like to guess: ")
fake[re] = guess #change the fake to represent that, EACH TIME IT OCCURS
print(''.join(fake))
This part is the culprit:
for re in range(0, len(myword)):#For statement to loop over the answer (not really over the answer, but the numerical index of the answer)
fake[re] = guess #change the fake to represent that, EACH TIME IT OCCURS
print(''.join(fake))
This code replace every element in fake with guess
Struggling with this exercise which must use a dictionary and count the number of times each word appears in a number of user inputs. It works in a fashion, but does not atomise each word from each line of user input. So instead of counting an input of 'happy days' as 1 x happy and 1 x days, it gives me 1 x happy days. I have tried split() along with the lower() but this converts the input to a list and I am struggling with then pouring that list into a dictionary.
As you may have guessed, I'm a bit of a novice, so all help would be greatly appreciated!
occurrences = {}
while True:
word = input('Enter line: ')
word = word.lower() #this is also where I have tried a split()
if word =='':
break
occurrences[word]=occurrences.get(word,0)+1
for word in (occurrences):
print(word, occurrences[word])
EDIT
Cheers for responses. This ended up being the final solution. They weren't worried about case and wanted the final results sorted().
occurrences = {}
while True:
words = input('Enter line: ')
if words =='':
break
for word in words.split():
occurrences[word]=occurrences.get(word,0)+1
for word in sorted(occurrences):
print(word, occurrences[word])
What you have is almost there, you just want to loop over the words when adding them to the dict
occurrences = {}
while True:
words = input('Enter line: ')
words = words.lower() #this is also where I have tried a split()
if words =='':
break
for word in words.split():
occurrences[word]=occurrences.get(word,0)+1
for word in (occurrences):
print(word, occurrences[word])
This line does not get executed: occurrences[word]=occurrences.get(word,0)+1
Because if it enters the if, it goes to the break and never executes that line. To make it be outside of the if don't indent it.
In general, the indentation of the posted code is messed up, I guess it's not really like that in your actual code.
Do you want line by line stats or do you want overall stats ? I'm guessing you want line by line, but you can also get overall stats easily by uncommenting a few lines in the following code:
# occurrences = dict() # create a dictionary here if yuo want to have incremental overall stats
while True:
words = input('Enter line: ')
if words =='':
break
word_list = words.lower().split()
print word_list
occurrences = dict() # create a dict here if you want line by line stats
for word in word_list:
occurrences[word] = occurrences.get(word,0)+1
## use the lines bellow if you want line by line stats
for k,v in occurrences.items():
print k, " X ", v
## use the lines bellow if you want overall stats
# for k,v in occurrences.items():
# print k, " X ", v
I'm trying to set a memory word game where the program reads a text file with 10 words. The program reads the file and creates a list of 9 out of the words .pop() the last word no.10. The words are randomly shuffled and then displayed again with a 2nd list of the same words randomly shuffled with the last word .pop() and the 1st removed is replacing the word (removed / substituted) - hope that sort of explains it.
I an having an issue regarding feeding back the right response whenter code hereen the user guesses the correct answer (it nots) everything else appears to be working.
import time
from random import shuffle
file =open('Words.txt', 'r')
word_list = file.readlines()
word_list [0:9]
shuffle(word_list)
extra_word=(word_list.pop())
print (extra_word)#substitute word for 2nd question (delete this line)
print '...............'
print (word_list)
print ('wait and now see the new list')
time.sleep(3)
print ('new lists')
word_list [0:9]
shuffle(word_list)
newExtra_word=(word_list.pop())
print (newExtra_word)#replace word for 1st question (delete this line)
word_list.insert(9,extra_word)# replace word
print (word_list)
This code above works fine (for what i want it to do..) The section below however:
#ALLOW FOR 3 GUESSES
user_answer = (raw_input('can you guess the replaced word: ')).lower()
count = 0
while count <=1:
if user_answer == newExtra_word:
print("well done")
break
else:
user_answer = (raw_input('please guess again: ')).lower()
count+=1
else:
print ('Fail, the answer is' + extra_word)
The code does allow for three guesses, but will not accept the removed list item. Does anyone have any ideas why?
Well, because your code above DOESN'T work the way you want it to.
file = open('Words.txt', 'r')
word_list = file.readlines()
# you should do file.close() here
word_list[0:9]
That last line doesn't actually do anything. It returns the first 10 elements in word_list but you never assign them to anything, so it's essentially a NOP. Instead do
word_list = word_list[0:9] # now you've removed the extras.
Probably better is to shuffle first so you have a truly random set of 10. Why 10? Why are we restricting the data? Oh well, okay...
# skipping down a good ways
word_list.insert(9, extra_word) # replace word
Why are we doing this? I don't really understand what this operation is supposed to do.
As for allowing three guesses:
count = 0
while count < 3:
user_answer = raw_input("Can you guess the replaced word: ").lower()
count += 1
if user_answer == newExtra_word:
print("well done")
break
else:
print("Sorry, the answer is " + extra_word)
Wait, did you catch that? You're checking the user input against newExtra_word then you're reporting the correct answer as extra_word. Are you sure your code logic works?
What it SOUNDS like you want to do is this:
with open("Words.txt") as inf:
word_list = [next(inf).strip().lower() for _ in range(11)]
# pull the first _11_ lines from Words.txt, because we're
# going to pop one of them.
word_going_in = word_list.pop()
random.shuffle(word_list)
print ' '.join(word_list)
random.shuffle(word_list)
word_coming_out = word_list.pop()
# I could do word_list.pop(random.randint(0,9)) but this
# maintains your implementation
word_list.append(word_going_in)
random.shuffle(word_list)
count = 0
while count < 3:
user_input = raw_input("Which word got replaced? ").lower()
count += 1
if user_input == word_coming_out:
print "Well done"
break
else:
print "You lose"
I am newbie to programming and python. I looked online for help and I doing as they say but I think I am making a mistake which I am not able to catch.
For now all I'm trying to do here is: if the word matches the length that user entered with the word in the file, make a list of those words. It sort of works if I replace userLength with the actual number but it's not working with variable userlength. I need that list later to develop Hangman.
Any help or recommendation on code will be great.
def welcome():
print("Welcome to the Hangman: ")
userLength = input ("Please tell us how long word you want to play : ")
print(userLength)
text = open("test.txt").read()
counts = Counter([len(word.strip('?!,.')) for word in text.split()])
counts[10]
print(counts)
for wl in text.split():
if len(wl) == counts :
wordLen = len(text.split())
print (wordLen)
print(wl)
filename = open("test.txt")
lines = filename.readlines()
filename.close()
print (lines)
for line in lines:
wl = len(line)
print (wl)
if wl == userLength:
words = line
print (words)
def main ():
welcome()
main()
The input function returns a string, so you need to turn userLength into an int, like this:
userLength = int(userLength)
As it is, the line wl == userLength is always False.
Re: comment
Here's one way to build that word list of words with the correct length:
def welcome():
print("Welcome to the Hangman: ")
userLength = int(input("Please tell us how long word you want to play : "))
words = []
with open("test.txt") as lines:
for line in lines:
word = line.strip()
if len(word) == userLength:
words.append(word)
input() returns a string py3.x , so you must convert it to int first.
userLength = int(input ("Please tell us how long word you want to play : "))
And instead of using readlines you can iterate over one line at once, it is memory efficient. Secondly use the with statement when handling files as it automatically closes the file for you.:
with open("test.txt") as f:
for line in f: #fetches a single line each time
line = line.strip() #remove newline or other whitespace charcters
wl = len(line)
print (wl)
if wl == userLength:
words = line
print (words)