I am trying to write a simple script that starts with a word and then keeps printing words that rhyme with the one before it (i.e. egg, aaberg, mpeg). It uses NLTK. However whilst running the code I get an error:
Traceback (most recent call last):
File "C:\Users\myname\Google Drive\Python codes\Rhyming words.py", line 58, in <module>
word_real = word[randint(0, len(word)-1)]
File "C:\Python27\lib\random.py", line 242, in randint
return self.randrange(a, b+1)
File "C:\Python27\lib\random.py", line 218, in randrange
raise ValueError, "empty range for randrange() (%d,%d, %d)" % (istart, istop, width)
ValueError: empty range for randrange() (0,0,0)
I have narrowed it down to one function, the main one, that returns a list of words that rhyme.
def rhyme(inp, level):
entries = nltk.corpus.cmudict.entries()
syllables = [(word, syl) for word, syl in entries if word == inp]
rhymes = []
for (word, syllable) in syllables:
rhymes += [word for word, pron in entries if pron[-level:] == syllable[-level:]]
return rhymes
When I do rhyme("egg", 1) it returns with a list of rhyming words. No problem right? But then if i do:
x = "egg"
rhyme(x, 1)
I get the error stated above. To paraphrase, it throws an error when I use a variable and I really don't know why.
Full code:
# -*- coding: cp1252 -*-
import nltk, time, os
from random import randint
###Words###
import urllib2
word_site = "http://svnweb.freebsd.org/csrg/share/dict/words?view=co&content-type=text/plain"
response = urllib2.urlopen(word_site)
txt = response.read()
WORDS = txt.splitlines()
###end WORDS###
def rhyme(inp, level):
entries = nltk.corpus.cmudict.entries()
syllables = [(word, syl) for word, syl in entries if word == inp]
rhymes = []
for (word, syllable) in syllables:
rhymes += [word for word, pron in entries if pron[-level:] == syllable[-level:]]
return rhymes
def text_file(mode):
if os.path.isfile("words.txt"):
words = open("words.txt", mode)
else:
words = open("words.txt", "w")
return words
def start_word():
words = text_file("r")
if open("words.txt", "r").readlines() == 0:
return WORDS[randint(0, len(WORDS)-1)]
else:
word = words.readlines()[len(words.readlines())-1]
return word[0:len(word)-2]
words.close()
def last_word(last_word):
words = text_file("a")
words.write(last_word+"\n")
words.close()
word_start = start_word()
#debug
print word_start, type(word_start)
while True:
word = rhyme(word_start, 1)
#debug
print word
if (len(word)-1) < 1:
word_real = word[randint(0, len(word)-1)]
print word_real
last_word(word_real)
word_start = word_real
time.sleep(0.3)
All that was wrong was a < instead of a > in:
if (len(word)-1) < 1:
word_real = word[randint(0, len(word)-1)]
You are generating an empty range here:
if len(word)-1) < 1:
word_real = word[randint(0, len(word)-1)]
so only if you have zero or one elements in word do you call randint(). The second argument then will be 0 or -1, and randint(0, -1) is invalid for that function.
You probably meant to use >= 1 instead. Rather than use randint(), use random.choice() to pick a random element from a list:
if word:
word_real = random.choice(word)
if word is true if the word list is not empty.
This does not have anything to do with using variables or not. The problem seems to be here:
if (len(word)-1) < 1:
word_real = word[randint(0, len(word)-1)]
You execute this part of code only when len(word)-1) < 1, i.e. you do randint(0, 0)!
You probably just mistakenly used < instead of >.
if (len(word)-1) > 1:
word_real = word[randint(0, len(word)-1)]
Or shorter:
if word:
word_real = random.choice(word)
Related
I am trying to make a job that takes in a text file, then counts the number of syllables in each word, then ultimately returns the top 10 words with the most syllables. I believe I have most of it down, but I am getting an error:
File "top_10_syllable_count.py", line 84, in get_syllable_count_pair return (syllables(word), word, ) TypeError: 'module' object is not callable.
Here is my code:
import re
from sys import stderr
from mrjob.job import MRJob
from mrjob.step import MRStep
WORD_RE = re.compile(r"[\w']+")
import syllables
class MRMostUsedWordSyllables(MRJob):
def steps(self):
return [
MRStep(mapper=self.word_splitter_mapper,
reducer=self.sorting_word_syllables),
MRStep(mapper=self.get_syllable_count_pair),
MRStep(reducer=self.get_top_10_reducer)
]
def word_splitter_mapper(self, _, line):
#for word in line.split():
for word in WORD_RE.findall(line):
yield(word.lower(), None)
def sorting_word_syllables(self, word, count):
count = 0
vowels = 'aeiouy'
word = word.lower().strip()
if word in vowels:
count +=1
for index in range(1,len(word)):
if word[index] in vowels and word[index-1] not in vowels:
count +=1
if word.endswith('e'):
count -= 1
if word.endswith('le'):
count+=1
if count == 0:
count +=1
yield None, (int(count), word)
def get_syllable_count_pair(self, _, word):
return (syllables(word), word, )
def get_top_10_reducer(self, count, word):
assert count == None # added for a guard
with_counts = [get_syllable_count_pair(w) for w in word]
# Sort the words by the syllable count
sorted_counts = sorted(syllables_counts, reverse=True, key=lambda x: x[0])
# Slice off the first ten
for t in sorted_counts[:10]:
yield t
if __name__ == '__main__':
import time
start = time.time()
MRMostUsedWordSyllables.run()
end = time.time()
print(end - start)
I believe my issue has to do with calling syllables in the get_syllable_count_pair function, but not sure how to correct it.
The syllables package has one function according to the documentation. You would call it like so.
syllables.estimate(word)
Your code would be like so:
return (syllables.estimate(word), word, )
I know there are already countless clones of Wordle. Nevertheless I try to program my own version.
In the function is_real_word it should be checked whether the entered word of the user occurs in the word list. If so, the variable check = True.
However, the FOR loop is always exited when the counter is at 1.
The file "5_letter_words.txt" contains 3 entries: wetter, wolle, watte
And last but not least also the return value for eingabewort is sometimes NONE. And I don't know why?
import random
def word_list():
wordle = []
with open("5_letter_words.txt", "r") as file:
for line in file:
myTuple = line.strip()
wordle.append(myTuple)
return wordle
def random_word(wordlist):
return random.choice(wordlist)
def is_real_word(guess, wordlist):
for word in wordlist:
if guess == word:
return True
return False
def check_guess(guess, randomword):
randomword_tuple = []
guess_tuple = []
length = len(randomword)
output = ["-"] * length
for index in range(length):
if guess[index] == randomword[index]:
output[index] = "X"
randomword = randomword.replace(guess[index], "-", 1)
for index in range(length):
if guess[index] in randomword and output[index] == "-":
output[index] = "O"
randomword = randomword.replace(guess[index], "-", 1)
return ''.join(output)
def next_guess(wordlist):
guess = input('Please enter a guess: ')
guess = guess.lower()
valid = is_real_word(guess, wordlist)
if valid == False:
print('Thats not a real word!')
next_guess(wordlist)
else:
return guess
def play():
target = []
target = word_list()
zufallswort = str()
zufallswort = random_word(target)
eingabewort = next_guess(target)
print('Eingabewort: ', eingabewort)
print('Zielwort: ', zufallswort)
play()
Could you check if your function word_list returns the list?
You dont give a clear path, only the file name.
If it works, try:
def is_real_word(guess, wordlist):
for word in wordlist:
if guess == word:
check = 1
break
return check
This function will search for anagrams in a list from a .txt file, I want to be able to check for anagrams and return all anagrams of the word that I input, and if it's not an anagram it will return the input, when I do it in the code below, it iterates through the for loop then ignores my first if statement and heads directly to my else statement. How can I fix this?
def find_in_dict():
input_word = input("Enter input string)")
sorted_word = ''.join(sorted(input_word.strip()))
a_word = ''.join((input_word.strip()))
word_file = open("filename", "r")
word_list = {}
for text in word_file:
simple_text = ''.join(sorted(text.strip()))
word_list.update({text.strip(): simple_text})
alist = []
for key, val in word_list.items():
if val == sorted_word:
alist.append(key)
return alist
else:
return "No words can be formed from:" + a_word
you are making a return statement in the if and else branch, that will break the for (because return invoked inside a function do exactly that, interrupt the execution and return the value) , so, don't do that, just ask if the word is equal, and in the end, check if there is none occurrences (empty list)
for text in word_file:
simple_text = ''.join(sorted(text.strip()))
word_list.update({text.strip(): simple_text})
alist = []
for key, val in word_list.items():
if val == sorted_word:
alist.append(key)
if alist == []: print("No words can be formed from: " + a_word)
program to check if word starts & ends with same letter
def match_letter():
count = 0
for word in words:
if len(word) >=2 and word[0] == word[-1]:
count = count + 1
return count
def main():
words = []
words_list = raw_input('Enter Words: ')
words_list = words_list().split()
for word in words_list:
words.append(word)
count = match_letter()
print 'letter matched %d ' %count
if __name__ == '__main__':
main()
this is my python code, giving an error
Traceback (most recent call last):
File "D:\Programming\Python\Python 2.7\same_letter.py", line 21, in <module>
main()
File "D:\Programming\Python\Python 2.7\same_letter.py", line 13, in main
words_list = words_list().split()
TypeError: 'str' object is not callable
i am very thankful if anyone can help me..
This line has an extra parentheses
words_list = words_list().split()
It could just be
words_list = words_list.split()
In fact, you have a number of extraneous steps, your code block
words = []
words_list = raw_input('Enter Words: ')
words_list = words_list().split()
for word in words_list:
words.append(word)
Could be reduced to:
words = raw_input('Enter Words: ').split()
And if I understand your question, I would solve this using slicing
def same_back_and_front(s):
return s[0] == s[-1] # first letter equals last letter
>>> words = ['hello', 'test', 'yay', 'nope']
>>> [word for word in words if same_back_and_front(word)]
['test', 'yay']
Thanx Cyber.. It works for me.
this code works for me exactly as i want
def match_letter(words):
count = 0
for word in words:
if len(word) >=2 and word[0] == word[-1]:
count = count + 1
return count
def main():
words = raw_input('Enter Words: ').split()
count = match_letter(words)
print 'letter matched %d ' %count
if __name__ == '__main__':
main()
Problem statement : Write a function called censor that takes two strings, text and word, as input. It should return the text with the word you chose replaced with asterisks
Here is my code,
def censor(text, word):
i = 0
j = 0
ans = ""
while i<len(text):
while text[j] == word[j]:
j = j + 1
if text[j+1] == " " or j+1 == len(text):
while i<j:
ans += "*"
i = i + 1
ans += " "
i = i + 1
else:
while text[j] != " ":
j = j + 1
while i<=j:
ans += text[i]
i = i + 1
i = i + 1
j = j + 1
return ans
print censor("how are you? you are not fine.","you")
But I am getting the following error,
Traceback (most recent call last):
File "python", line 27, in <module>
File "python", line 7, in censor
IndexError: string index out of range
This is much more complicated than it needs to be. You can just do this:
def censor(text, censored_word):
return text.replace(censored_word, '*'*len(censored_word))
>>> censor('How are you? Are you okay?', 'you')
'How are ***? Are *** okay?'
If you don't want the word youth to be censored but you do want you to be censored, here's how:
def censor(text, censored_word):
repl = '*'*len(censored_word)
return ' '.join([repl if word == censored_word else word for word in text.split()])
If you want to have multiple censored words:
def censor(text, censored_words):
return ' '.join(['*'*len(word) if word in censored_words else word for word in text.split()])
When dealing with index errors, it is often helpful to print out the index and figure out why the index has a value not within the required bounds.
It's good to use string replace in python for replacing the string.
In your case, you should make use of word's length to match word in the text as:
def censor(text, word):
i = 0
j = 0
ans = ""
wl=len(word)
while i<(len(text)):
if word==text[i:i+wl]:
ans=ans+'*'*wl
i=i+wl
else:
ans=ans+text[i]
i = i + 1
return ans
print censor("how are you? you are not fine.","you")