I'm fairly new to Python and one of the practice projects I'm trying to do is converting sentences into pig latin. The original project was just converting words into pig latin, but I want to expand this into converting sentences.
Here's the code I have so far:
import sys
print("Pig Latin Maker")
VOWELS = 'aeiouy'
while True:
word = input ("Write a Word: ")
if word[0] in VOWELS:
pig_Latin = word + 'way'
else:
pig_Latin = word[1:] + word[0] + 'ay'
print ()
print ("{}".format(pig_Latin), file=sys.stderr)
end = input ("\n\n Press N\n")
if end.lower() == "n":
sys.exit()
The plan is to modify this so it splits all the words in the input sentence, converts each word to pig latin, and then spits it back out as one sentence but I'm not really sure how to do that.
I'm using Python 3.8. Any help is appreciated! Thank you.
You could split the sentence by the space character into separate strings each containing a word. You can then apply your current algorithm to every single word in that sentence. str has a method split which returns a list.
To get the words in a list, use listofwords = input('Write your sentence: ').split().
Then, you can combine the list of pig-latin words doing print(' '.join(listofpiglatin)).
import sys
print("Pig Latin Maker")
VOWELS = 'aeiouy'
while True:
listofwords = input ("Write a Sentence: ").split() # splits by spaces
listofpiglatin = []
for word in listofwords:
if word[0] in VOWELS:
pig_Latin = word + 'way'
else:
pig_Latin = word[1:] + word[0] + 'ay'
listofpiglatin.append(pig_Latin) # adds your new pig-latin word to our list
print()
print(' '.join(listofpiglatin)) # spits the words back as a sentence
end = input ("\n\n Press n")
if end.lower() == "n":
sys.exit()
I hope that this helps you learn!
Put your algorithm into a function:
def makePigLatin(word):
<your code here>
return latinWord
As other users mentioned, split the input and assign to a list:
words = input('blah').split()
Then apply your function to each word in the list:
translatedWords = map(makePigLatin, words)
Print them back out by joining them together:
print(' '.join(translatedWords))
Related
I'm trying to make an acronym program where the user can enter 1 word per line and after entering a blank space the program will output the word created by the first letter of each word. It is printing a whitespace after the output which I don't want. Any Ideas on how to remove that? More information below:
E.g
User input:
Word: Hello
Word: World
Desired output:
Hello World <-- whitespace here that I don't want
-- HW
My Current Code that works:
words = []
word = input('Word: ')
while word:
words.append(word)
word = input('Word: ') #Word input
for word in words:
print(word, end=" ") #displays all words on one line
# Printing a white space ^
# Wanting to print this code on a new line
first_letters = ''.join([word[0] for word in words])
new=first_letters.upper()
print("\n-- " + new)
You're almost there. Combining what you had with num and print:
for word in words:
print(word[:1], end="") # Display all first letters without spaces.
This code does everything you want
words = []
word = input('Word: ')
while word:
words.append(word)
word = input('Word: ') #Word input
print(' '.join(words))
first_letters = ''.join([word[0] for word in words])
new=first_letters.upper()
print("-- " + new)
Simply this?
words = ['Hello','World']
print(' '.join(w for w in words))
print('-- '+''.join(w[0] for w in words))
Given array of strings words. There are several approaches to get first letters of the words. Few of them are below.
First approach
first_letters = ''
for word in words:
first_letters += word[0]
print(first_letters)
Second approach
first_letters = ''.join([word[0] for word in words])
print(first_letters)
I have this code
#Ask for word
w = input("Type in a word to create acronym with spaces between the words:")
#Seperate the words to create acronym
s = w.split(" ")
letter = s[0]
#print answer
print(s.upper(letter))
And I know that I need a for loop to loop over the words to get the first letter of each word but I can't figure out how to do it I tried many different types but I kept getting errors.
Try this. It prints a concatenated version of the first letter of each word.
w = input("Type in a word to create acronym with spaces between the words:")
print(''.join([e[0] for e in w.split()]).upper())
Try this
w = input("Type a phrase with a space between the words:")
w_up_split = w.upper().split()
acronym = ""
for i in w_up_split:
acronym += (i[0])
print(acronym)
for word in w.split(" "):
first_letter = word[0]
print(first_letter.upper())
In the code that you gave you are taking the first word in a list of lists.
s = w.split(" ")
letter = s[0]
If someone input 'Hi how are you' this s would equal
s == ["Hi"]["how"]["are"]["you"]
And then letter would equal the first index of s which would be ["Hi"]
You want to go through each word and take each letter
acronym = []
for x in s:
acronym.append(x[0])
Would get what you want.
I'm new to programming and I'm having a hard time understanding how to ask the user if they want to run it again?
def pigLatin(word):
"""
Function that converts word into Pig Latin form
"""
# Checking for starting letter as vowel
if word[0] in ['a','e','i','o','u']:
return word + "way"
# Checking for vowel index
for i in range(1, len(word)):
# Checking for vowels(including y)
if word[i] in ['a','e','i','o','u','y']:
# Updating vowel index
vowelIndex = i;
break;
# Forming pig lating word
return word[vowelIndex:] + word[0:vowelIndex] + "ay";
def removePunctuation(text):
"""
Removes punctuation from text
"""
# List of punctuation characters
punctuations = ['(', ')', '?', ':', ';', ',', '.', '!', '/', '"', "'"]
# Iterating over punctuations
for ch in punctuations:
# Replacing punctuations
text = text.replace(ch, "")
# Returning text
return text
def main():
"""
Main function
"""
# Reading line of text
text = input("\n Enter a line of text: ")
# Removing punctuation
text = removePunctuation(text)
# Converting to lower case
text = text.lower()
print("\n\n Pig Latin form: \n");
# Iterating over words
for word in text.split(" "):
# Converting word to Pig Latin form
word = pigLatin(word)
# Printing word
print(word, end = " ");
print("\n");
# Calling main function
main()
How exactly would I add a loop that asks the user to continue or not? I'm new to programming and im very confused. I also don't understand how to add the English form of the sentence before the pig latin form??
can someone please help!
you can use a while loop in your main and a string like -1 to exit
def main():
while True:
"""
Main function
"""
# Reading line of text
text = input("\n Enter a line of text or -1 to exit: ")
if text == '-1':
exit(0)
# Removing punctuation
text = removePunctuation(text)
# Converting to lower case
text = text.lower()
print("\n\n Pig Latin form: \n");
# Iterating over words
for word in text.split(" "):
# Converting word to Pig Latin form
word = pigLatin(word)
# Printing word
print(word, end = " ");
print("\n");
A simple solution might look something like this:
while True:
main()
response = input("Continue?")
if response != 'y':
break
You'll probably want to be a little less strict about the inputs you accept.
I think it would be better practice to put this loop inside your main function (and have a check on __name__ before invoking it), but this at least demonstrates what the loop would look like.
This question already has answers here:
How to modify list entries during for loop?
(10 answers)
Closed 6 years ago.
I'm taking a sentence and turning it into pig latin, but when I edit the words in the list it never stays.
sentence = input("Enter a sentence you want to convert to pig latin")
sentence = sentence.split()
for words in sentence:
if words[0] in "aeiou":
words = words+'yay'
And when I print sentence I get the same sentence I put in.
another way to do it (includes some fixes)
sentence = input("Enter a sentence you want to convert to pig latin: ")
sentence = sentence.split()
for i in range(len(sentence)):
if sentence[i][0] in "aeiou":
sentence[i] = sentence[i] + 'yay'
sentence = ' '.join(sentence)
print(sentence)
Because you did not change sentence
So to get the results you want
new_sentence = ''
for word in sentence:
if word[0] in "aeiou":
new_sentence += word +'yay' + ' '
else:
new_sentence += word + ' '
So now print new_sentence
I set this up to return a string, if you would rather have a list that can be accomplished as easily
new_sentence = []
for word in sentence:
if word[0] in "aeiou":
new_sentence.append(word + 'yay')
else:
new_sentence.append(word)
If you are working with a list and you want to then convert the list to a string then just
" ".join(new_sentence)
It does not seem as though you are updating sentence.
sentence = input("Enter a sentence you want to convert to pig latin")
sentence = sentence.split()
# lambda and mapping instead of a loop
sentence = list(map(lambda word: word+'yay' if word[0] in 'aeiou' else word, sentence))
# instead of printing a list, print the sentence
sentence = ' '.join(sentence)
print(sentence)
PS. Kinda forgot some things about Python's for loop so I didn't use it. Sorry
the question asks to have to user enter a one word string, then randomize the place of the letters in the word, for example, "hello" can turn into "elhlo"
import random
def word_jumble():
word = raw_input("Enter a word: ")
new_word = ""
for ch in range(len(word)):
r = random.randint(0,len(word)-1)
new_word += word[r]
word = word.replace(word[r],"",1)
print new_word
def main():
word_jumble()
main()
I got the program from someone else, but have no idea how it works. can someone explain to me please? I understand everything before
new_word += word[r]
The code is unnecessarily complex, maybe this will be easier to understand:
import random
word = raw_input("Enter a word: ")
charlst = list(word) # convert the string into a list of characters
random.shuffle(charlst) # shuffle the list of characters randomly
new_word = ''.join(charlst) # convert the list of characters back into a string
r is a randomly selected index in the word, so word[r] is a randomly selected character in the word. What the code does is it selects a random character from word and appends it to new_word (new_word += word[r]). The next line removes the character from the original word.
If you use a bytearray, you can use random.shuffle directly
import random
word = bytearray(raw_input("Enter a word: "))
random.shuffle(word)