After python pyglatin upgrade


#1

I cannot seem to edit my code in order for it to print consonant blends at the beginning of a word, to the end. Ex: I want a word like gloves to print ovesglay instead it print lovesgay.
Below is my code and I'm not sure what to put in consonant_blends = word[?] Or in its' corresponding elif statement, or what o can do to make it work.

VOWELS = ('a', 'e', 'i', 'o', 'u')
lst = ['sh', 'gl', 'ch', 'ph', 'tr', 'br', 'fr', 'bl', 'gr', 'st', 'cl' 'pl', 'fl', 'th']

def convert_word(word):

first_letter = word[0]

consonant_blend = word[?]

if first_letter in VOWELS:

##return word + "yay"

elif consonant_blend in lst:

##return word[?] + "ay"

else:

##return word[1:] + word[0] + "ay"

def convert_sentence(sentence):

list_of_words = sentence.split(' ')

new_sentence = ""

for word in in list_of_words:

##new_sentence = new_sentence + convert_word(word)
##new_sentence = new_sentence + " "

return new_sentence

print "Type in a sentence, and it'll get converted to Pig-Latin!"
print "Please don't use punctuation or numbers"
print "Also, we can't handle uppercase/lowercase yet, so lowers only please!"
print

text = raw_input()

print
print convert_sentence(text)

I know it won't work now but before when Id try it would print this if my input was my gloves are warm
yay lovesgay areyay armway
I'd like it to print: yay ovesglay areyay arm way

How do I do this, and I understand I don't have every single consonant blend in my lst but just for the common words.

Please help!


#2

ymay not just yay my apologies on the failed example lol


#3

Codify your code and I'll attempt to set you right, I just can't look at code that isn't properly formmatted.

Format your code by,

```python
# code here
``` # end

OR

Highlight Code hit ctrl + alt + c


#4

Yes, @papaodeuce, here is a link that may help you out.


#5

@papaodeuce

Yuppers you can totally do what you want to, do something like the following for ease of use.

word = 'Sheet'
start_of_words = ['sh', 'gl', 'ch', 'ph', 'tr']
if word.lower()[:2] in start_of_words:
    # DO AMAZING STUFFZ HERE!!!
    print(word)

Easy, well now it is for you I guess. Anything else?

Also, if you want different out put for each set of letters you would do,

word = 'Sheet'
start_of_words = {'sh': 'all', 'gl': 'bee', 'ch': 'tree', 'ph': 'army', 'tr': 'apple'} #Or what ever you want as the value for the key
# Then you would go
new_word = word[2:] + start_of_words[word[:2]

Generally you would use it with an if statement or a try/exception/else/finally statement if your start was not in your dict. That is up to you though.


#6
VOWELS = ('a', 'e', 'i', 'o', 'u')
lst = ['sh', 'gl', 'ch', 'ph', 'tr', 'br', 'fr', 'bl', 'gr', 'st', 'cl' 'pl', 'fl']

def convert_word(word):
    first_letter = word[0]
    consonant_blend = word[?]
    if first_letter in VOWELS:
        return word + "yay"
    elif consonant_blend in lst:
        return word[?] + "ay"
    else:
        return word[1:] + word[0] + "ay"

def convert_sentence(sentence):
    list_of_words = sentence.split(' ')
    new_sentence = ""
    for word in list_of_words:
        new_sentence = new_sentence + convert_word(word)
        new_sentence = new_sentence + " "
    return new_sentence

print "Type in a sentence, and it'll get converted to Pig-Latin!"
print "Please don't use punctuation or numbers"
print "Also, we can't handle uppercase/lowercase yet, so lowers only please!"
print

text = raw_input()

print
print convert_sentence(text)

#7

@papaodeuce

You do not need to worry about punctuation or the like, I will show you how.

# The re module is to use regular expressions
import re

# Here we define the vowel sting, the r denotes it as a raw string
vowels = r'AEIOUaeiou'


def pig_latin_translator(word):
    """
    This function will out put our pig latin translations,
    all work is to be done here on the word in question.
    :param word: Pass the word to modify
    :return: Returns the modified word.
    """
    return (word[1:] + word[0] + 'ay') if word[0] not in vowels \
        else (word[1:] + word[0] + 'way')


def deconstruct_text(text):
    """
    This function uses the regex module to find and separate all words
    in a string.

    \b == Boundary of words
    [] == Finds what is specified inside
    ^ == start of the string
    \W Finds all word characters ie any alphanumeric character
    \d_ Finds all digits and excludes them
    + == It will find just one of that particular spot.

    :param text:
    :return:
    """
    temp = re.findall(r'\b[^\W\d_]+\b', text)
    return [word for word in temp]


def pig_latin_worker(data):
    """
    This function will do all the work of passing the data to our deconstruct and then
    passing it into the translator one word at a time.
    :param data: Pass any data, if it is not a str or list it will kick it back
    :return: Returns status or updated string.
    """
    if type(data) not in (str, list):
        return "Failed to enter valid data."
    else:
        return ' '.join((pig_latin_translator(word) if len(word) > 1
                         else word) for word in deconstruct_text(data))

if __name__ == '__main__':
    while True:
        _temp = input('Please enter a word or phrase to convert to Pig Latin.\n')
        print(pig_latin_worker(_temp))
        _ans = input('\nIf you would like to translate more stuff please enter: y: yes, n: no\n')
        if _ans not in 'y':
            break

Ok, I'm going to post another post in a bit about what all this does, so fear not. For right now try to figure out what everything does and post what you think.

We can of course add more functionality to out code at a moments notice, take what I have here and see what you can do with it.

EDIT:

I updated the code with comments so it should be easier to figure some stuff out.


#8

@zeziba so i plugged this in to ideone to run (since im waiting for my cygwin to finish downloading, and it turns things into the pig-latin phrase however i'm back to the original problem. I used my original statement to translate "my gloves are warm" and it returned "ymay lovesgay areway armway" my original problem was that i could not make gloves (or other words with consonant blends at the beginning) then properly translate to pig-latin. but i do like your code as it works minus this little issue.


#9

@papaodeuce

Like I said just add to it, just change the pig latin function to include what you want.


#10

ill definitely try my skills are mediocre at best, but one last question before my attempt numero deuce(play on my name wink wink) for your suggestion of adding word = 'sheet' example would that then replace my lst and would i add this method before or after my def convert_word?


#11

@papaodeuce

I would replace the list with a dictionary with your select concenate as the the key and what you want to have as the value,

# Dict of replacement words
consonants = {'gl': 'glay', 'wa': 'way'}
# Then just edit the pig Latin function to
def pig_latin_translator(word):
    # This will look in the dict for the first two letters and if the key matches
    # will get the length and then start from there for the beginning of the word.
    return word[len(consonants[word[:2]]):] + consonants[word]

Easy enough? You can then just add more key:values to your dict to increase it's capacity for words.


#12

Awesome thank you so much I'll mess with it manyana and let you know how it goes !!!! Fingers crossed


#14

so here's what i got. it worked for the consonant blend, but then i realized that there are triple blends and now i dont have enough variables in the script to nullify the con blend if it falls within triple blend.
my, new/quazi working code is below:

VOWELS = ('a', 'e', 'i', 'o', 'u')
consonant_blends = {'bl': 'blay', 'br' : 'bray', 'ch' : 'chay', 'cl' : 'clay', 'cr' : 'cray', 'dr' : 'dray', 'fl' : 'flay', 'fr' : 'fray', 'gl' : 'glay', 'gr' : 'gray', 'pl' : 'play', 'pr' : 'pray', 'sc' : 'scay', 'sh' : 'shay', 'sk' : 'skay', 'sl' : 'slay', 'sm' : 'smay', 'sn' : 'snay', 'sp' : 'spay', 'st' : 'stay', 'sw' : 'sway', 'th' : 'thay', 'tr' : 'tray', 'tw' : 'tway', 'wh' : 'whay', 'wr' : 'wray'}
triple_blends = {'sch' : 'schay', 'scr' : 'scray', 'shr' : ''shray', 'sph' : 'sphay', 'spl' : 'splay', 'spr' : 'spray', 'squ' : 'squay', 'str' : 'stray', 'thr' : 'thray'}

def convert_word(word):
    first_letter = word[0]
    if first_letter in VOWELS:
        return word + "yay"
    elif word[0:2] in consonant_blends.keys():
        return word[2:len(word)] + consonant_blends[word[0:2]]
    elif word[0:3] in triple_blends.keys(): #here's my problem, also i don't think i have enough variables to make sure triple_blends works if a consonant_blends key is apart of the triple_blends key
        return word[3:len(word)] + consonant_blends[word[0:3]]
    else:
        return word[1:] + word[0] + "ay"

def convert_sentence(sentence)
    list_of_words = sentence.split(' ')
    new_sentence = ""
    for word in list_of_words:
        new_sentence = new_sentence + convert_word(word)
        new_sentence = new_sentence + " "
    return new_sentence

print "Type in a sentence, and it'll get converted to Pig-Latin!"
print "Please don't use punctuation or numbers."
print "Also, we can't handle uppercase/lowercase yet, so lowers only please!"
print

text = raw_input()

print
print convert_sentence(text)

ex my output for the word scream is reamscray, i want words with triple consonants at the beginning to print ex eamscray. how would i do this with my code, or by editing something in my code to get it to work?


#15

@papaodeuce

I changed a few things and got rid of the dictionary, all you are doing is looking for specific starts to your words, because of this I went to a list with what we are looking for. If you use a dict then you would use a unique string for each entry, if it is just the start with 'ay' added to it we can shorten the code considerably by doing so.

Pig Latin:

import re

VOWELS = 'aeiou'
consonant_blends = ['bl', 'wr', 'sw', 'gr', 'wh', 'st', 'sp', 'cl', 'th',
                    'pr', 'tr', 'dr', 'sh', 'sm', 'fl', 'sl', 'cr', 'sc',
                    'fr', 'gl', 'br', 'ch', 'sn', 'sk', 'tw', 'pl']
triple_blends = ['thr', 'str', 'spl', 'shr', 'scr', 'sch', 'squ', 'sph', 'spr']

find_word = re.compile(r'\b[^\W\d_]+\b')


def convert_word(word):
    if word[0:3] in triple_blends:
        return word[3:] + word[3:] + 'ay'
    elif word[0:2] in consonant_blends:
        return word[2:] + word[2:] + 'ay'
    elif word[0] in VOWELS:
        return word + "yay"
    else:
        return word[1:] + word[0] + "ay"


def convert_sentence(sentence):
    """
    This function will only take words out of the string, so you can enter what you want.
    Just remember that though, you can add functionality with the regex module
    to find and replace any conjunctions used to their full value.
    :param sentence: Text string to be converted
    :return: Returns converted String
    """
    work = ' '.join(convert_word(word) for word in find_word.findall(sentence))
    return '{0}{1}'.format(work[0].upper(), work[1:])

# Try to get used to using this, eventually you will want to import a module
# and if you program it like this you will not have your test code execute.
print(convert_sentence('Apples and oranges'))
if __name__ == '__main__':
    # Use the newline '\n' to add spaces to your text and then use \ to continue your entry like here
    print "Type in a sentence, and it'll get converted to Pig-Latin!\n" \
          "Please don't use punctuation or numbers.\n" \
          "Also, we can't handle uppercase/lowercase yet, so lowers only please!"

    print convert_sentence(raw_input())

You should learn how to use the regular expression module for this, you can write expressions that find the words that have what you are looking for easily, and complied regexs run just as fast as anything else here and a good chunk of the time faster because they are converted to C code.

Other than that I removed redundant code, and shortened a few things. Also, you should take note that I am commenting my code. It is a fantastic habit to get into for not only yourself but for others who try to read your code. It will also help you understand what you are really doing in your code.

The best note of all, if your code looks fantastic and you can most definitely improve on it. You do not have to use anything I suggest, just go for it. Once you are happy with what your code does then you are good, until then break it fix and expand it and you will have something amazing to show people.

If you need anything else feel free to ask.


#16

@zeziba

so i tried your latest example and it appeared to repeat the word missing which ever prefix ex scream = eameamay, however i figured it out with the most recent code i provided. I changed the elif statement regarding the triple_blends to the first if statement under convert_word and made the consonant_blends the elif and after testing it a few times in cygwin it seems to work with both triple and consonant blends. Now i just have to figure out how to include punctuation and capitalization lol!

thank you for the help. this is the first non codecademy script ive ever written for fun and so im very pleased with myself and will strive to make this one better as to include capitalization and punctuation.