I'm trying to convert a sentence to pig latin but I can;t get it to work.
Conditions:
1. If it starts with a vowel, add way to the word (e.g eagle become eagleway)
2. If it starts with a consonant, check the second character and so on for as long as it's a consonant, keep checking and strip it out and put it at the end. (e.g grain becomes aingr)
Here is my code so far:
x = "The apple is extremely tasty. Great!"
y = x.split()
for i in y:
if(i[0] == "a" or i[0]=="e" or i[0]=="i" or i[0]=="o" or i[0]=="u"):
print(i+"way", end = " ")
I managed to do part 1. but I can't figure out part 2. I don't understand how to go through the chars and strip the whole part.
Any help is appreciated.
Thanks.
Firstly, pick better variable names:
sentence = "The apple is extremely tasty. Great!"
words = sentence.split()
for word in words:
Secondly, you can simplify your first check:
if word[0] in "aeiou":
print("{0}way".format(word), end=" ")
Finally, you could use while and slicing to move characters from the start of the word to the end:
else:
while word[0] not in "aeiou":
word = "".join((word[1:], word[0]))
print(word, end=" ")
Note that this still doesn't quite do what you want:
eTh appleway isway extremelyway asty.t eat!Gr
I will leave dealing with letter cases and punctuation as an exercise; I suggest making everything one case or the other and removing all punctuation before iterating through words.
Related
How can I capitalize the first letter of a input sentence in python?
Output has to be: Enter sentence to be capitalized:+ input sentence
input_string =input("Enter sentence to be capitalized: ")
def capitalize_first(input_string):
output=input_string.split('.')
i=0
while i<len(output)-1:
result=output[i][0].upper()+output[i][1:]+"."
print("Enter sentence to be capitalized:"+result)
How about input_string.title()?
input_string =input("Enter sentence to be capitalized: ")
def capitalize_first(input_string):
result = input_string.title()
print("Enter sentence to be capitalized:"+result)
This built-in method only capitalises the first character and keeps other ones lower, just like how titles work.
As you can see, the extra capitals in THIS IS AN AMAZING are changed.
>>> input_string = "Hello World THIS IS AN AMAZING day!!!"
>>> input_string.title()
>>> 'Hello World This Is An Amazing Day!!!'
In my opinion there are many ways to do so, but title() is the easiest. You can use upper() inside a for loop which iterating the input string, or even capitalize(). If the goal is to capitalise only the first letter of every word. Then you can't use above methods since they capitalise the word in traditional way (first letter is capitalise and others in simple letters regardless what user entered). To avoid that and keep any capitalise letters inside a word as it is, just like user entered.
Then this might be a solution
inputString=input("Your statement enter value or whatever")
seperatedString=inputString.split()
for i in seperatedString:
i[0].upper()
print("Anything you want to say" + i)
sentence="test Sentence"
print(sentence.title()) #makes the first letter of every word in sentence capital
print(sentence[0].upper()+sentence[1:] ) #retains case of other charecters
print(sentence.capitalize()) #makes all other charecters lowercase
Output:
Test Sentence
Test Sentence
Test sentence
Answer your specific question
def modify_string(str1):
sentence_list=str1.split('.')
modify_this=input("Enter sentence to be modified: ")
for idx, item in enumerate(sentence_list):
modify_this_copy=modify_this
if item.lower().strip()==modify_this.lower().strip():
sentence_list[idx]=modify_this_copy[0].upper()+modify_this_copy[1:]
return '. '.join(sentence_list)
string1="hello. Nice to meet you. hello. Howdy."
print(modify_string(string1))
Output
Enter sentence to be modified: hello
Hello. Nice to meet you. Hello. Howdy.
This is the question I was given to solve:
Create a program inputs a phrase (like a famous quotation) and prints all of the words that start with h-z.
I solved the problem, but the first two methods didn't work and I wanted to know why:
#1 string index out of range
quote = input("enter a 1 sentence quote, non-alpha separate words: ")
word = ""
for character in quote:
if character.isalpha():
word += character.upper()
else:
if word[0].lower() >= "h":
print(word)
word = ""
else:
word = ""
I get the IndexError: string index out of range message for any words after "g". Shouldn't the else statement catch it? I don't get why it doesn't, because if I remove the brackets [] from word[0], it works.
#2: last word not printing
quote = input("enter a 1 sentence quote, non-alpha separate words: ")
word = ""
for character in quote:
if character.isalpha():
word += character.upper()
else:
if word.lower() >= "h":
print(word)
word = ""
else:
word = ""
In this example, it works to a degree. It eliminates any words before 'h' and prints words after 'h', but for some reason doesn't print the last word. It doesn't matter what quote i use, it doesn't print the last word even if it's after 'h'. Why is that?
You're calling on word[0]. This accesses the first element of the iterable string word. If word is empty (that is, word == ""), there is no "first element" to access; thus you get an IndexError. If a "word" starts with a non-alphabetic character (e.g. a number or a dash), then this will happen.
The second error you're having, with your second code snippet leaving off the last word, is because of the approach you're using for this problem. It looks like you're trying to walk through the sentence you're given, character by character, and decide whether to print a word after having read through it (which you know because you hit a space character. But this leads to the issue with your second approach, which is that it doesn't print the last string. That's because the last character in your sentence isn't a space - it's just the last letter in the last word. So, your else loop is never executed.
I'd recommend using an entirely different approach, using the method string.split(). This method is built-in to python and will transform one string into a list of smaller strings, split across the character/substring you specify. So if I do
quote = "Hello this is a sentence"
words = quote.split(' ')
print(words)
you'll end up seeing this:
['Hello', 'this', 'is', 'a', 'sentence']
A couple of things to keep in mind on your next approach to this problem:
You need to account for empty words (like if I have two spaces in a row for some reason), and make sure they don't break the script.
You need to account for non-alphanumeric characters like numbers and dashes. You can either ignore them or handle them differently, but you have to have something in place.
You need to make sure that you handle the last word at some point, even if the sentence doesn't end in a space character.
Good luck!
Instead of what you're doing, you can Iterate over each word in the string and count how many of them begin in those letters. Read about the function str.split(), in the parameter you enter the divider, in this case ' ' since you want to count the words, and that returns a list of strings. Iterate over that in the loop and it should work.
# Reading line of text
text = input("Enter text: ")
print("English: " ,text)
# Removing punctuation
text = removePunctuation(text)
# Converting to lower case
text = text.lower()
# Iterating over words
for word in text.split(" "):
# Converting word to Pig Latin form
word = pigLatin(word)
# Printing word
print(word, end = " ");
How can I get it to say Pig: and then the Pig Latin form? Every time i try this, it just adds the Pig Latin transformation to the previous word.
You're trying to make one variable do two things at once.
If you want to use the old value later (in your print) then quit destroying the original value:
pl_word = pigLatin(word)
print (word, pl_word)
print("Pig:", word)
Next time, please use capital letters and some markdown... https://stackoverflow.com/editing-help
I am trying to output the total of how many words start with a letter 'a' in a list from a separate text file. I'm looking for an output such as this.
35 words start with a letter 'a'.
However, i'm outputting all the words that start with an 'a' instead of the total with my current code. Should I be using something other than a for loop?
So far, this is what I have attempted:
wordsFile = open("words.txt", 'r')
words = wordsFile.read()
wordsFile.close()
wordList = words.split()
print("Words:",len(wordList)) # prints number of words in the file.
a_words = 0
for a_words in wordList:
if a_words[0]=='a':
print(a_words, "start with the letter 'a'.")
The output I'm getting thus far:
Words: 334
abate start with the letter 'a'.
aberrant start with the letter 'a'.
abeyance start with the letter 'a'.
and so on.
You could replace this with a sum call in which you feed 1 for every word in wordList that starts with a:
print(sum(1 for w in wordList if w.startswith('a')), 'start with the letter "a"')
This can be further trimmed down if you use the boolean values returned by startswith instead, since True is treated as 1 in these contexts the effect is the same:
print(sum(w.startswith('a') for w in a), 'start with the letter "a"')
With your current approach, you're not summing anything, you're simply printing any word that matches. In addition, you're re-naming a_word from an int to the contents of the list as you iterate through it.
Also, instead of using a_word[0] to check for the first character, you could use startswith(character) which has the same effect and is a bit more readable.
You are using the a_words as the value of the word in each iteration and missing a counter. If we change the for loop to have words as the value and reserved a_words for the counter, we can increment the counter each time the criteria is passed. You could change a_words to wordCount or something generic to make it more portable and friendly for other letters.
a_words = 0
for words in wordList:
if words[0]=='a':
a_words += 1
print(a_words, "start with the letter 'a'.")
sum(generator) is a way to go, but for completeness sake, you may want to do it with list comprehension (maybe if it's slightly more readable or you want to do something with words starting with a etc.).
words_starting_with_a = [word for word in word_list if word.startswith('a')]
After that you may use len built-in to retrieve length of your new list.
print(len(words_starting_with_a), "words start with a letter 'a'")
Simple alternative solution using re.findall function(without splitting text and for loop):
import re
...
words = wordsFile.read()
...
total = len(re.findall(r'\ba\w+?\b', words))
print('Total number of words that start with a letter "a" : ', total)
Okay so I am writing a program for python involving myself to make pig latin. Here is my code so far:
pig = input("What do you want to translate in pig latin? ")
pig = pig.lower()
for word in pig.split(' '):
last_char = word[-1]
word = word[:-1]
print(word + "ay")
How would I be able to grab the last character of any string regardless of it's length and place that character in front of the newly formed pig latin word?
Getting the last character of string is as simple as word[-1]. To add last character to the string you have to use string concatenation.
Have a look at inserting characters at the start and end of a string
Do you want to 'translate' several words or only one? If only one, you don't need a for loop. If several, you have to make sure you include print function in loop (otherwise, it will print only the last word). Also you can shorten your code by not using last_char variable (it wouldn't change readability much).
One word:
pig = input("What do you want to translate in pig latin? ")
pig = pig.lower()
word = pig[-1] + pig[:-1]
print(word + "ay")
Several words:
pig = input("What do you want to translate in pig latin? ")
pig = pig.lower()
for word in pig.split(' '):
word = word[-1] + word[:-1]
print(word + "ay")