Translate English to Pig Latin | PIG_LATIN.PYPig Latin TranslatorPython Pig Latin TranslatorDiamond in the...
What's the difference between a share and a stock?
Is the interior of a Bag of Holding actually an extradimensional space?
Who are these people in this satirical cartoon of the Congress of Verona?
What is the majority of the UK Government as of 2019-09-04?
First Number to Contain Each Letter
Why does the UK Prime Minister need the permission of Parliament to call a general election?
Entering the US with dual citizenship but US passport is long expired?
Why did Boris Johnson call for new elections?
What is the source of the fear in the Hallow spell's extra Fear effect?
How do I anonymously report the Establishment Clause being broken?
Is a paralyzed creature limp or rigid?
RAW, Is the "Finesse" trait incompatible with unarmed attacks?
How can I oppose my advisor granting gift authorship to a collaborator?
Are there mathematical concepts that exist in the fourth dimension, but not in the third dimension?
Are language and thought the same?
Is it risky to move from broad geographical diversification into investing mostly in less developed markets?
Combinatorics problems that can be solved more easily using probability
Is it possible to observe space debris with Binoculars?
Can anyone find an image of Henry Bolingbroke's Sovereygne Feather Seal?
A Meal fit for a King
What drugs were used in England during the High Middle Ages?
'Hard work never hurt anyone' Why not 'hurts'?
Why don't they build airplanes from 3D printer plastic?
Do 643,000 Americans go bankrupt every year due to medical bills?
Translate English to Pig Latin | PIG_LATIN.PY
Pig Latin TranslatorPython Pig Latin TranslatorDiamond in the rough! Finding Gems in the rocksCCC Rövarspråket (Pig Latin) translatorHaskell - Pig Latin TranslatorPig Latin Translator in PythonPig latin translating programJava Pig Latin TranslatorPig Latin AnslatortrayPig Latin in Rust
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ margin-bottom:0;
}
$begingroup$
Converting English to the pseudo-language Pig Latin. Not the strictest form of Pig Latin but it most likely will accurately output an argument in Pig Latin. Got idea from Github. Is there any way I can improve it concisely?
def pig_latin(message):
consonants = ['b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'y',
'z']
new_message = ''
for word in message.split():
ay = ['a', 'y']
listed_word = list(word)
word_copy = word
moved_consonants = ''
for letter in listed_word.copy():
if letter.lower() == 'y':
if letter in word_copy[0]:
moved_consonants += letter
listed_word.remove(letter)
else:
break
elif letter.lower() in consonants:
moved_consonants += letter
listed_word.remove(letter)
else:
break
listed_word.append('-' + moved_consonants + ''.join(ay))
new_message += ''.join(listed_word) + ' '
return new_message
print(pig_latin('Can you read pig latin?'))
python beginner python-3.x programming-challenge pig-latin
$endgroup$
add a comment |
$begingroup$
Converting English to the pseudo-language Pig Latin. Not the strictest form of Pig Latin but it most likely will accurately output an argument in Pig Latin. Got idea from Github. Is there any way I can improve it concisely?
def pig_latin(message):
consonants = ['b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'y',
'z']
new_message = ''
for word in message.split():
ay = ['a', 'y']
listed_word = list(word)
word_copy = word
moved_consonants = ''
for letter in listed_word.copy():
if letter.lower() == 'y':
if letter in word_copy[0]:
moved_consonants += letter
listed_word.remove(letter)
else:
break
elif letter.lower() in consonants:
moved_consonants += letter
listed_word.remove(letter)
else:
break
listed_word.append('-' + moved_consonants + ''.join(ay))
new_message += ''.join(listed_word) + ' '
return new_message
print(pig_latin('Can you read pig latin?'))
python beginner python-3.x programming-challenge pig-latin
$endgroup$
4
$begingroup$
To the close voter (/ presumably downvoter), they said they got the idea from a github list, not the implementation. I don't see an authorship issue here.
$endgroup$
– Carcigenicate
7 hours ago
add a comment |
$begingroup$
Converting English to the pseudo-language Pig Latin. Not the strictest form of Pig Latin but it most likely will accurately output an argument in Pig Latin. Got idea from Github. Is there any way I can improve it concisely?
def pig_latin(message):
consonants = ['b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'y',
'z']
new_message = ''
for word in message.split():
ay = ['a', 'y']
listed_word = list(word)
word_copy = word
moved_consonants = ''
for letter in listed_word.copy():
if letter.lower() == 'y':
if letter in word_copy[0]:
moved_consonants += letter
listed_word.remove(letter)
else:
break
elif letter.lower() in consonants:
moved_consonants += letter
listed_word.remove(letter)
else:
break
listed_word.append('-' + moved_consonants + ''.join(ay))
new_message += ''.join(listed_word) + ' '
return new_message
print(pig_latin('Can you read pig latin?'))
python beginner python-3.x programming-challenge pig-latin
$endgroup$
Converting English to the pseudo-language Pig Latin. Not the strictest form of Pig Latin but it most likely will accurately output an argument in Pig Latin. Got idea from Github. Is there any way I can improve it concisely?
def pig_latin(message):
consonants = ['b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'y',
'z']
new_message = ''
for word in message.split():
ay = ['a', 'y']
listed_word = list(word)
word_copy = word
moved_consonants = ''
for letter in listed_word.copy():
if letter.lower() == 'y':
if letter in word_copy[0]:
moved_consonants += letter
listed_word.remove(letter)
else:
break
elif letter.lower() in consonants:
moved_consonants += letter
listed_word.remove(letter)
else:
break
listed_word.append('-' + moved_consonants + ''.join(ay))
new_message += ''.join(listed_word) + ' '
return new_message
print(pig_latin('Can you read pig latin?'))
python beginner python-3.x programming-challenge pig-latin
python beginner python-3.x programming-challenge pig-latin
edited 6 hours ago
200_success
136k21 gold badges173 silver badges443 bronze badges
136k21 gold badges173 silver badges443 bronze badges
asked 8 hours ago
Mikey AkamiheMikey Akamihe
1206 bronze badges
1206 bronze badges
4
$begingroup$
To the close voter (/ presumably downvoter), they said they got the idea from a github list, not the implementation. I don't see an authorship issue here.
$endgroup$
– Carcigenicate
7 hours ago
add a comment |
4
$begingroup$
To the close voter (/ presumably downvoter), they said they got the idea from a github list, not the implementation. I don't see an authorship issue here.
$endgroup$
– Carcigenicate
7 hours ago
4
4
$begingroup$
To the close voter (/ presumably downvoter), they said they got the idea from a github list, not the implementation. I don't see an authorship issue here.
$endgroup$
– Carcigenicate
7 hours ago
$begingroup$
To the close voter (/ presumably downvoter), they said they got the idea from a github list, not the implementation. I don't see an authorship issue here.
$endgroup$
– Carcigenicate
7 hours ago
add a comment |
2 Answers
2
active
oldest
votes
$begingroup$
First, at the top you list all the consonants out. There are two things that can be improved here:
Since you only use it to check whether or not something is a consonant, it should be a set. It's much more efficient to to a membership lookup on a set than it is to do one on a list. Just replace the
[]
with{}
.
consonants = {'b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'y', 'z'}
Second, there's a slightly less painful way to generate those letters. Python's
string
module contains aascii_lowercase
built-in that holds'abcdefghijklmnopqrstuvwxyz'
. You can use that along with a set of vowels to limit what letters need to be hard-coded:
import string as s
vowels = {'a', 'e', 'i', 'o', 'u'}
consonants = set(s.ascii_lowercase) - vowels # Consonants are the set of letters, minus the vowels
I personally prefer this way.
You could also just change your algorithm to use vowels
directly.
Just to clear something up,
word_copy = word
does not create a copy of word
. This just creates a second name for the word
string. For Strings this doesn't matter because Strings are immutable, but with a mutable object, this will bite you:
my_list = []
list_copy = my_list # Does not actually create a copy!
my_list.append(1)
print(my_list, list_copy) # prints [1] [1]
Notice how both lists were added to. This happens because there's actually only one list. Both names are referring to the same list.
For the sake of clarity, I'd rename it to say what it's purpose is. Offhand though, I can't see the need for word_copy
at all! It would make sense if it was being used as an accumulator for a loop or something, but the only time its ever used is at word_copy[0]
, and since you never reassign word
, you could just do word[0]
. I'd simply get rid of word_copy
.
Along the same lines, I'd reconsider ay
. The name you've given it is exactly as descriptive as the string it contains, and is only ever used in one place. At the very least, I'd rename it to something meaningful:
pig_latin_suffix = ['a', 'y']
I'll also note that there's no reason to use a list of Strings here instead of a multi-character String. They behave the same in this case:
" ".join(['a', 'y'])
'a y'
" ".join("ay")
'a y'
Strings are iterable just like lists are.
I think pig_latin
is too big. It's doing two main jobs: breaking the message into words, and processing the words. I would make the processing step its own function:
def process_word(word):
ay = ['a', 'y']
listed_word = list(word)
word_copy = word
moved_consonants = ''
for letter in listed_word.copy():
if letter.lower() == 'y':
if letter in word_copy[0]:
moved_consonants += letter
listed_word.remove(letter)
else:
break
elif letter.lower() in consonants:
moved_consonants += letter
listed_word.remove(letter)
else:
break
listed_word.append('-' + moved_consonants + ''.join(ay))
return ''.join(listed_word)
def pig_latin(message):
new_message = ''
for word in message.split():
processed_word = process_word(word)
new_message += processed_word + ' '
return new_message
process_word
could arguably be broken down further. This is already much better though. The immediate benefit is now you can test individual words, and not have to worry about how the rest of the code will react:
print(process_word("Can")) # Prints 'an-Cay'
$endgroup$
add a comment |
$begingroup$
As this is a simple text transformation, the regular-expression module re
is your friend.
Processing letters one at a time is h-a-r-d. It would be simpler to process things one word at a time, as suggested by @Carcigenicate.
The re.sub(pattern, repl, text, ...)
function is interesting in that it allows you to specify a string or a function for the replacement. As a first approximation:
import re
def pig_latin(text):
def transform(match):
first, rest = match.group(1, 2)
if first.lower() in "aeiou":
return first + rest + 'way'
else:
return rest + first + 'ay'
return re.sub(r'(w)(w*)', transform, text)
print(pig_latin("Can you read pig latin?"))
anCay ouyay eadray igpay atinlay?
Here, the regex is extracting entire words with two capturing groups. The first group is simply the first letter w
, an the second group is the rest of the letters (if any) in the word w*
. The match
is passed to the transform
function, from which groups #1 and #2 are extracted and assigned to first
and rest
. If the first
letter is a vowel, the replacement text is generated one way; if not it is generated a second way. The returned value is used as the replacement in the re.sub(...)
call.
The transform
function can easily be modified to include the -
, if desired, as well as additional special handling of y
, if required.
$endgroup$
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "196"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f227479%2ftranslate-english-to-pig-latin-pig-latin-py%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
2 Answers
2
active
oldest
votes
2 Answers
2
active
oldest
votes
active
oldest
votes
active
oldest
votes
$begingroup$
First, at the top you list all the consonants out. There are two things that can be improved here:
Since you only use it to check whether or not something is a consonant, it should be a set. It's much more efficient to to a membership lookup on a set than it is to do one on a list. Just replace the
[]
with{}
.
consonants = {'b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'y', 'z'}
Second, there's a slightly less painful way to generate those letters. Python's
string
module contains aascii_lowercase
built-in that holds'abcdefghijklmnopqrstuvwxyz'
. You can use that along with a set of vowels to limit what letters need to be hard-coded:
import string as s
vowels = {'a', 'e', 'i', 'o', 'u'}
consonants = set(s.ascii_lowercase) - vowels # Consonants are the set of letters, minus the vowels
I personally prefer this way.
You could also just change your algorithm to use vowels
directly.
Just to clear something up,
word_copy = word
does not create a copy of word
. This just creates a second name for the word
string. For Strings this doesn't matter because Strings are immutable, but with a mutable object, this will bite you:
my_list = []
list_copy = my_list # Does not actually create a copy!
my_list.append(1)
print(my_list, list_copy) # prints [1] [1]
Notice how both lists were added to. This happens because there's actually only one list. Both names are referring to the same list.
For the sake of clarity, I'd rename it to say what it's purpose is. Offhand though, I can't see the need for word_copy
at all! It would make sense if it was being used as an accumulator for a loop or something, but the only time its ever used is at word_copy[0]
, and since you never reassign word
, you could just do word[0]
. I'd simply get rid of word_copy
.
Along the same lines, I'd reconsider ay
. The name you've given it is exactly as descriptive as the string it contains, and is only ever used in one place. At the very least, I'd rename it to something meaningful:
pig_latin_suffix = ['a', 'y']
I'll also note that there's no reason to use a list of Strings here instead of a multi-character String. They behave the same in this case:
" ".join(['a', 'y'])
'a y'
" ".join("ay")
'a y'
Strings are iterable just like lists are.
I think pig_latin
is too big. It's doing two main jobs: breaking the message into words, and processing the words. I would make the processing step its own function:
def process_word(word):
ay = ['a', 'y']
listed_word = list(word)
word_copy = word
moved_consonants = ''
for letter in listed_word.copy():
if letter.lower() == 'y':
if letter in word_copy[0]:
moved_consonants += letter
listed_word.remove(letter)
else:
break
elif letter.lower() in consonants:
moved_consonants += letter
listed_word.remove(letter)
else:
break
listed_word.append('-' + moved_consonants + ''.join(ay))
return ''.join(listed_word)
def pig_latin(message):
new_message = ''
for word in message.split():
processed_word = process_word(word)
new_message += processed_word + ' '
return new_message
process_word
could arguably be broken down further. This is already much better though. The immediate benefit is now you can test individual words, and not have to worry about how the rest of the code will react:
print(process_word("Can")) # Prints 'an-Cay'
$endgroup$
add a comment |
$begingroup$
First, at the top you list all the consonants out. There are two things that can be improved here:
Since you only use it to check whether or not something is a consonant, it should be a set. It's much more efficient to to a membership lookup on a set than it is to do one on a list. Just replace the
[]
with{}
.
consonants = {'b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'y', 'z'}
Second, there's a slightly less painful way to generate those letters. Python's
string
module contains aascii_lowercase
built-in that holds'abcdefghijklmnopqrstuvwxyz'
. You can use that along with a set of vowels to limit what letters need to be hard-coded:
import string as s
vowels = {'a', 'e', 'i', 'o', 'u'}
consonants = set(s.ascii_lowercase) - vowels # Consonants are the set of letters, minus the vowels
I personally prefer this way.
You could also just change your algorithm to use vowels
directly.
Just to clear something up,
word_copy = word
does not create a copy of word
. This just creates a second name for the word
string. For Strings this doesn't matter because Strings are immutable, but with a mutable object, this will bite you:
my_list = []
list_copy = my_list # Does not actually create a copy!
my_list.append(1)
print(my_list, list_copy) # prints [1] [1]
Notice how both lists were added to. This happens because there's actually only one list. Both names are referring to the same list.
For the sake of clarity, I'd rename it to say what it's purpose is. Offhand though, I can't see the need for word_copy
at all! It would make sense if it was being used as an accumulator for a loop or something, but the only time its ever used is at word_copy[0]
, and since you never reassign word
, you could just do word[0]
. I'd simply get rid of word_copy
.
Along the same lines, I'd reconsider ay
. The name you've given it is exactly as descriptive as the string it contains, and is only ever used in one place. At the very least, I'd rename it to something meaningful:
pig_latin_suffix = ['a', 'y']
I'll also note that there's no reason to use a list of Strings here instead of a multi-character String. They behave the same in this case:
" ".join(['a', 'y'])
'a y'
" ".join("ay")
'a y'
Strings are iterable just like lists are.
I think pig_latin
is too big. It's doing two main jobs: breaking the message into words, and processing the words. I would make the processing step its own function:
def process_word(word):
ay = ['a', 'y']
listed_word = list(word)
word_copy = word
moved_consonants = ''
for letter in listed_word.copy():
if letter.lower() == 'y':
if letter in word_copy[0]:
moved_consonants += letter
listed_word.remove(letter)
else:
break
elif letter.lower() in consonants:
moved_consonants += letter
listed_word.remove(letter)
else:
break
listed_word.append('-' + moved_consonants + ''.join(ay))
return ''.join(listed_word)
def pig_latin(message):
new_message = ''
for word in message.split():
processed_word = process_word(word)
new_message += processed_word + ' '
return new_message
process_word
could arguably be broken down further. This is already much better though. The immediate benefit is now you can test individual words, and not have to worry about how the rest of the code will react:
print(process_word("Can")) # Prints 'an-Cay'
$endgroup$
add a comment |
$begingroup$
First, at the top you list all the consonants out. There are two things that can be improved here:
Since you only use it to check whether or not something is a consonant, it should be a set. It's much more efficient to to a membership lookup on a set than it is to do one on a list. Just replace the
[]
with{}
.
consonants = {'b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'y', 'z'}
Second, there's a slightly less painful way to generate those letters. Python's
string
module contains aascii_lowercase
built-in that holds'abcdefghijklmnopqrstuvwxyz'
. You can use that along with a set of vowels to limit what letters need to be hard-coded:
import string as s
vowels = {'a', 'e', 'i', 'o', 'u'}
consonants = set(s.ascii_lowercase) - vowels # Consonants are the set of letters, minus the vowels
I personally prefer this way.
You could also just change your algorithm to use vowels
directly.
Just to clear something up,
word_copy = word
does not create a copy of word
. This just creates a second name for the word
string. For Strings this doesn't matter because Strings are immutable, but with a mutable object, this will bite you:
my_list = []
list_copy = my_list # Does not actually create a copy!
my_list.append(1)
print(my_list, list_copy) # prints [1] [1]
Notice how both lists were added to. This happens because there's actually only one list. Both names are referring to the same list.
For the sake of clarity, I'd rename it to say what it's purpose is. Offhand though, I can't see the need for word_copy
at all! It would make sense if it was being used as an accumulator for a loop or something, but the only time its ever used is at word_copy[0]
, and since you never reassign word
, you could just do word[0]
. I'd simply get rid of word_copy
.
Along the same lines, I'd reconsider ay
. The name you've given it is exactly as descriptive as the string it contains, and is only ever used in one place. At the very least, I'd rename it to something meaningful:
pig_latin_suffix = ['a', 'y']
I'll also note that there's no reason to use a list of Strings here instead of a multi-character String. They behave the same in this case:
" ".join(['a', 'y'])
'a y'
" ".join("ay")
'a y'
Strings are iterable just like lists are.
I think pig_latin
is too big. It's doing two main jobs: breaking the message into words, and processing the words. I would make the processing step its own function:
def process_word(word):
ay = ['a', 'y']
listed_word = list(word)
word_copy = word
moved_consonants = ''
for letter in listed_word.copy():
if letter.lower() == 'y':
if letter in word_copy[0]:
moved_consonants += letter
listed_word.remove(letter)
else:
break
elif letter.lower() in consonants:
moved_consonants += letter
listed_word.remove(letter)
else:
break
listed_word.append('-' + moved_consonants + ''.join(ay))
return ''.join(listed_word)
def pig_latin(message):
new_message = ''
for word in message.split():
processed_word = process_word(word)
new_message += processed_word + ' '
return new_message
process_word
could arguably be broken down further. This is already much better though. The immediate benefit is now you can test individual words, and not have to worry about how the rest of the code will react:
print(process_word("Can")) # Prints 'an-Cay'
$endgroup$
First, at the top you list all the consonants out. There are two things that can be improved here:
Since you only use it to check whether or not something is a consonant, it should be a set. It's much more efficient to to a membership lookup on a set than it is to do one on a list. Just replace the
[]
with{}
.
consonants = {'b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'y', 'z'}
Second, there's a slightly less painful way to generate those letters. Python's
string
module contains aascii_lowercase
built-in that holds'abcdefghijklmnopqrstuvwxyz'
. You can use that along with a set of vowels to limit what letters need to be hard-coded:
import string as s
vowels = {'a', 'e', 'i', 'o', 'u'}
consonants = set(s.ascii_lowercase) - vowels # Consonants are the set of letters, minus the vowels
I personally prefer this way.
You could also just change your algorithm to use vowels
directly.
Just to clear something up,
word_copy = word
does not create a copy of word
. This just creates a second name for the word
string. For Strings this doesn't matter because Strings are immutable, but with a mutable object, this will bite you:
my_list = []
list_copy = my_list # Does not actually create a copy!
my_list.append(1)
print(my_list, list_copy) # prints [1] [1]
Notice how both lists were added to. This happens because there's actually only one list. Both names are referring to the same list.
For the sake of clarity, I'd rename it to say what it's purpose is. Offhand though, I can't see the need for word_copy
at all! It would make sense if it was being used as an accumulator for a loop or something, but the only time its ever used is at word_copy[0]
, and since you never reassign word
, you could just do word[0]
. I'd simply get rid of word_copy
.
Along the same lines, I'd reconsider ay
. The name you've given it is exactly as descriptive as the string it contains, and is only ever used in one place. At the very least, I'd rename it to something meaningful:
pig_latin_suffix = ['a', 'y']
I'll also note that there's no reason to use a list of Strings here instead of a multi-character String. They behave the same in this case:
" ".join(['a', 'y'])
'a y'
" ".join("ay")
'a y'
Strings are iterable just like lists are.
I think pig_latin
is too big. It's doing two main jobs: breaking the message into words, and processing the words. I would make the processing step its own function:
def process_word(word):
ay = ['a', 'y']
listed_word = list(word)
word_copy = word
moved_consonants = ''
for letter in listed_word.copy():
if letter.lower() == 'y':
if letter in word_copy[0]:
moved_consonants += letter
listed_word.remove(letter)
else:
break
elif letter.lower() in consonants:
moved_consonants += letter
listed_word.remove(letter)
else:
break
listed_word.append('-' + moved_consonants + ''.join(ay))
return ''.join(listed_word)
def pig_latin(message):
new_message = ''
for word in message.split():
processed_word = process_word(word)
new_message += processed_word + ' '
return new_message
process_word
could arguably be broken down further. This is already much better though. The immediate benefit is now you can test individual words, and not have to worry about how the rest of the code will react:
print(process_word("Can")) # Prints 'an-Cay'
edited 5 hours ago
answered 7 hours ago
CarcigenicateCarcigenicate
6,6171 gold badge19 silver badges43 bronze badges
6,6171 gold badge19 silver badges43 bronze badges
add a comment |
add a comment |
$begingroup$
As this is a simple text transformation, the regular-expression module re
is your friend.
Processing letters one at a time is h-a-r-d. It would be simpler to process things one word at a time, as suggested by @Carcigenicate.
The re.sub(pattern, repl, text, ...)
function is interesting in that it allows you to specify a string or a function for the replacement. As a first approximation:
import re
def pig_latin(text):
def transform(match):
first, rest = match.group(1, 2)
if first.lower() in "aeiou":
return first + rest + 'way'
else:
return rest + first + 'ay'
return re.sub(r'(w)(w*)', transform, text)
print(pig_latin("Can you read pig latin?"))
anCay ouyay eadray igpay atinlay?
Here, the regex is extracting entire words with two capturing groups. The first group is simply the first letter w
, an the second group is the rest of the letters (if any) in the word w*
. The match
is passed to the transform
function, from which groups #1 and #2 are extracted and assigned to first
and rest
. If the first
letter is a vowel, the replacement text is generated one way; if not it is generated a second way. The returned value is used as the replacement in the re.sub(...)
call.
The transform
function can easily be modified to include the -
, if desired, as well as additional special handling of y
, if required.
$endgroup$
add a comment |
$begingroup$
As this is a simple text transformation, the regular-expression module re
is your friend.
Processing letters one at a time is h-a-r-d. It would be simpler to process things one word at a time, as suggested by @Carcigenicate.
The re.sub(pattern, repl, text, ...)
function is interesting in that it allows you to specify a string or a function for the replacement. As a first approximation:
import re
def pig_latin(text):
def transform(match):
first, rest = match.group(1, 2)
if first.lower() in "aeiou":
return first + rest + 'way'
else:
return rest + first + 'ay'
return re.sub(r'(w)(w*)', transform, text)
print(pig_latin("Can you read pig latin?"))
anCay ouyay eadray igpay atinlay?
Here, the regex is extracting entire words with two capturing groups. The first group is simply the first letter w
, an the second group is the rest of the letters (if any) in the word w*
. The match
is passed to the transform
function, from which groups #1 and #2 are extracted and assigned to first
and rest
. If the first
letter is a vowel, the replacement text is generated one way; if not it is generated a second way. The returned value is used as the replacement in the re.sub(...)
call.
The transform
function can easily be modified to include the -
, if desired, as well as additional special handling of y
, if required.
$endgroup$
add a comment |
$begingroup$
As this is a simple text transformation, the regular-expression module re
is your friend.
Processing letters one at a time is h-a-r-d. It would be simpler to process things one word at a time, as suggested by @Carcigenicate.
The re.sub(pattern, repl, text, ...)
function is interesting in that it allows you to specify a string or a function for the replacement. As a first approximation:
import re
def pig_latin(text):
def transform(match):
first, rest = match.group(1, 2)
if first.lower() in "aeiou":
return first + rest + 'way'
else:
return rest + first + 'ay'
return re.sub(r'(w)(w*)', transform, text)
print(pig_latin("Can you read pig latin?"))
anCay ouyay eadray igpay atinlay?
Here, the regex is extracting entire words with two capturing groups. The first group is simply the first letter w
, an the second group is the rest of the letters (if any) in the word w*
. The match
is passed to the transform
function, from which groups #1 and #2 are extracted and assigned to first
and rest
. If the first
letter is a vowel, the replacement text is generated one way; if not it is generated a second way. The returned value is used as the replacement in the re.sub(...)
call.
The transform
function can easily be modified to include the -
, if desired, as well as additional special handling of y
, if required.
$endgroup$
As this is a simple text transformation, the regular-expression module re
is your friend.
Processing letters one at a time is h-a-r-d. It would be simpler to process things one word at a time, as suggested by @Carcigenicate.
The re.sub(pattern, repl, text, ...)
function is interesting in that it allows you to specify a string or a function for the replacement. As a first approximation:
import re
def pig_latin(text):
def transform(match):
first, rest = match.group(1, 2)
if first.lower() in "aeiou":
return first + rest + 'way'
else:
return rest + first + 'ay'
return re.sub(r'(w)(w*)', transform, text)
print(pig_latin("Can you read pig latin?"))
anCay ouyay eadray igpay atinlay?
Here, the regex is extracting entire words with two capturing groups. The first group is simply the first letter w
, an the second group is the rest of the letters (if any) in the word w*
. The match
is passed to the transform
function, from which groups #1 and #2 are extracted and assigned to first
and rest
. If the first
letter is a vowel, the replacement text is generated one way; if not it is generated a second way. The returned value is used as the replacement in the re.sub(...)
call.
The transform
function can easily be modified to include the -
, if desired, as well as additional special handling of y
, if required.
answered 5 hours ago
AJNeufeldAJNeufeld
12k1 gold badge10 silver badges36 bronze badges
12k1 gold badge10 silver badges36 bronze badges
add a comment |
add a comment |
Thanks for contributing an answer to Code Review Stack Exchange!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
Use MathJax to format equations. MathJax reference.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f227479%2ftranslate-english-to-pig-latin-pig-latin-py%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
4
$begingroup$
To the close voter (/ presumably downvoter), they said they got the idea from a github list, not the implementation. I don't see an authorship issue here.
$endgroup$
– Carcigenicate
7 hours ago