I am trying to make an up language translator. Simple task for me in python. Or so i thought. If you are unaware, up language is when you take a word and say it while adding up before every vowel. for example, Andrew would be Upandrupew. I am trying to find out how find all of the vowels in a user submitted word, and put up before them. Is there a way to cut up a word before all vowels. so excellent would be exc ell ent? thanks.
maybe
VOWELS = 'aeiou'
def up_it(word):
letters = []
for letter in word:
if letter.lower() in VOWELS:
letters.append('Up')
letters.append(letter)
return ''.join(letters)
can be simplified to
def up_it(word):
return ''.join('up'+c if c.lower() in 'aeiou' else c for c in word)
You could do that with a regex:
import re
a = "Hello World."
b = re.sub("(?i)([aeiou])", "up\\1", a)
The (?i) makes it case-insensitive. \\1 refers to the character that was matched inside ([aeiou]).
''.join(['up' + v if v.lower() in 'aeiou' else v for v in phrase])
for vowel in [“a“,“e“,“i“,“o“,“u“]:
Word = Word.replace(vowel,“up“+vowel)
print(Word)
import re
sentence = "whatever"
q = re.sub(r"([aieou])", r"up\1", sentence, flags=re.I)
vowels = ['a', 'e', 'i', 'o', 'u']
def upped_word(word):
output = ''
for character in word:
if character.lower() in vowels:
output += "up"
output += character
return output
Here is a one-liner for the entire problem
>>> "".join(('up' + x if x.upper() in 'AEIOU' else x for x in 'andrew'))
'upandrupew'
Here's one way of doing it.
wordList = list(string.lower())
wordList2 = []
for letter in wordList:
if letter in 'aeiou':
upLetter = "up" + letter
wordList2.append(upLetter)
else:
wordList2.append(letter)
"".join(wordList2)
Create a list of letters (wordList), iterate through those letters and append it to a second list, which is joined at the end.
Returns:
10: 'upandrupew'
In one line:
"".join(list("up"+letter if letter in "aeiou" else letter for letter in list(string.lower())))
I'd probably go with RegExp but there are already many answers using it. My second choice is the map function, witch is better then iterate through every letter.
>>> vowels = 'aeiou'
>>> text = 'this is a test'
>>> ''.join(map(lambda x: 'up%s'%x if x in vowels else x, text))
'thupis upis upa tupest'
>>>
def is_vowel(word):
''' Check if `word` is vowel, returns bool. '''
# Split word in two equals parts
if len(word) % 2 == 0:
parts = [word[0:len(word)/2], word[len(word)/2:]]
else:
parts = [word[0:len(word)/2], word[(len(word)/2)+1:]]
# Check if first part and reverse second part are same.
if parts[0] == parts[1][::-1]:
return True
else:
return False
This is a smart solution which helps you to count and find vowels in input string:
name = input("Name:- ")
counter = []
list(name)
for i in name: #It will check every alphabet in your string
if i in ['a','e','i','o','u']: # Math vowels to your string
print(i," This is a vowel")
counter.append(i) # If he finds vowels then he adds that vowel in empty counter
else:
print(i)
print("\n")
print("Total no of words in your name ")
print(len(name))
print("Total no of vowels in your name ")
print(len(counter))
Related
Hey guys so I'm writing a code for text message abbreviations and these are the following criteria:
Spaces are maintained, and each word is encoded individually. A word is a consecutive string of alphabetic characters.
If the word is composed only of vowels, it is written exactly as in the original message.
If the word has at least one consonant, write only the consonants that do not have another consonant immediately before them. Do not write any vowels.
The letters considered vowels in these rules are 'a', 'e', 'i', 'o' and 'u'. All other letters are considered consonants.
I have written a code and checked it but it is failing for the condition where if the word is composed only of vowels, it is written exactly as in the original message. My code currently is taking out all of the vowels. Like for this example, "aeiou bcdfghjklmnpqrstvwxyz" the code should return "aeiou b"
I tried using another helper function to determine when a word is all vowels but it isn't working. Any suggestions on how to implement something that could make this work? Thanks!
def Vowel(x):
vowels = "a" "e" "i" "o" "u"
value = 0
for ch in x:
if x == vowels:
value = value + 1
return value
def isVowel(phrase):
vowel = "a" "e" "i" "o" "u"
value = 0
for ch in phrase:
if ch in vowel:
value = value + 1
return value
def noVowel(ch):
vowel = "a" "e" "i" "o" "u"
value = 0
for i in ch:
if ch not in vowel:
value = value + 1
return value
def transform(word):
before = 'a'
answer = ""
for ch in word:
if Vowel(ch):
answer += ch
if noVowel(ch) and isVowel(before):
answer += ch
before = ch
return answer
def getMessage(original):
trans = ""
for word in original.split():
trans = trans + " " + transform(word)
trans = trans.strip()
return trans
if __name__ == '__main__':
print(getMessage("aeiou b"))
Your three Vowel-functions are all using a disfunctional for-loop and are highly redundant. Also Vowel() would always return 0, as x may never be a tuple of five vowels.
You would need only one function that just returns True if the character is a vowel and False if it is not. Then, you can use this function in the if-blocks in transform:
def Vowel(x):
vowels = ["a","e","i","o","u"]
return x.lower() in vowels ## True if x is a vowel (upper or lower case)
def transform(word):
before = 'a'
answer = ""
for ch in word:
if Vowel(ch):
answer += ch
if not Vowel(ch) and Vowel(before):
answer += ch
before = ch
return answer
You have not identified what to do with words that have both consonants and vowels...if you provide a few more example inputs and outputs, I might decide to change my code, but this is what I have come up with so far.
I have used regex:
(\b[aeiou]*\b) : finds vowel only words
([bcdfghjklmnpqrstvwxyz]*) : looks for groups of consonants.
The for-loop : helps to return the vowel-only words, or the first letter of the consonant groups.
import re
strings_to_test = ["aeiou bcdfghjklmnpqrstvwxyz ae hjgfd a",
"gg jjjjopppddjk eaf"]
pattern = re.compile(r"(\b[aeiou]*\b)|([bcdfghjklmnpqrstvwxyz]*)")
for line in strings_to_test:
results = []
match_list = pattern.findall(line)
for m in match_list:
if m[0]:
# word of vowels found
results.append(m[0])
elif m[1]:
#consonants found
results.append(m[1][0])
print(results)
OUTPUT:
['aeiou', 'b', 'ae', 'h', 'a']
['g', 'j', 'p', 'f']
This function receives a string as input and should return the number of syllables in the string.
This function has following conditions:
1. Number of syllables is equal to the number of vowels
2. Two or more consecutive vowels count only as one.
3. One or more vowels at the end of the word are not counted.
This is what I've so far but clearly I'm still missing a lot. I'm not sure how to continue here, so I hope you guys can help.
def syllables(word):
vowels = ['a','e','i','o','u','y']
# Delete ending vowel of the word since they don't count in number of syllables
# I've no idea how to remove all ending vowels though
word = word[:-1]
# List with vowels that appear in the word
vowelsList = [x for x in vocals if x in word]
N = []
for i in word:
if i in vowels:
N += i
N = len(N)
return N
print(syllables("bureau"))
# Should print "1" but prints "3" instead
I suggest you the following simple code:
def syllables(word):
vowels = ['a', 'e', 'i', 'o', 'u', 'y']
N = 0
previousLetterIsAVowel = False
# Perform a loop on each letter of the word
for i in word.lower():
if i in vowels:
# Here it is a vowel
# Indicate for the next letter that it is preceded by a vowel
# (Don't count it now as a syllab, because it could belong to a group a vowels ending the word)
previousLetterIsAVowel = True
else:
# Here: it is not a vowel
if previousLetterIsAVowel:
# Here it is preceded by a vowel, so it ends a group a vowels, which is considered as a syllab
N += 1
# Indicate for the next letter that it is not preceded by a vowel
previousLetterIsAVowel = False
return N
print(syllables("bureau")) # it prints 1
print(syllables("papier")) # it prints 2
print(syllables("ordinateur")) # it prints 4
print(syllables("India")) # it prints 1
I also provide a one-line style solution using regex, easily readable too if you know a little bit about regex. It simply counts the number of groups of consecutive vowels that are followed by a consonant:
import re
def syllables(word):
return len(re.findall('[aeiouy]+[bcdfghjklmnpqrstvwxz]', word.lower()))
To check the last vowel you can try something like this (I wouldn't iterate as you're going to loose whole syllables): -> EX: Italian word "Aia" (threshing floor)
if word[-1] in vocals:
word=word[:-1]
-- sorry but I didn't manage to put 'code' into comments so a posted an answer
I would go for:
def syllables(word):
def isVowel(c):
return c.lower() in ['a','e','i','o','u','y']
# Delete ending vowel of the word since they don't count in number of syllables
while word and isVowel(word[-1]):
word = word[:-1]
lastWasVowel = False
counter = 0
for c in word:
isV = isVowel(c)
# skip multiple vowels after another
if lastWasVowel and isV:
continue
if isV:
# found one
counter += 1
lastWasVowel = True
else:
# reset vowel memory
lastWasVowel = False
return counter
Stolen from LaurentH:
print(syllables("bureau")) # prints 1
print(syllables("papier")) # prints 2
print(syllables("ordinateur")) # prints 4
print(syllables("I")) # prints 0
I think we have return 1 if there is previousLetterIsAVowel and N returns 0. Example word Bee.
In Addition to Laurent H. answer
if N == 0 and previousLetterIsAVowel:
return 1
else:
return N
I have created the program for the most frequent vowel in a string but the problem that i am having is i want to print only one letter for the most frequent vowel, not both. My code is displayed below:
from collections import Counter
words = input("Enter a line of text: ")
vowel = "aeiouAEIOU"
x = Counter(c for c in words.upper() if c in vowel)
most = {k: x[k] for k in x if x[k] == max(x.values())}
for i in most:
vowel = i
y = most[i]
print("The most occuring vowel is:",vowel, "with",y,"occurences")
if vowel != words:
print("No vowels found in user input")
When i run the code for example i enter "aa ee" it will print:
The most occuring vowel is: A with 2 occurences
The most occuring vowel is: E with 2 occurrences
I only want it to print either A or E?
Why you don't simply use Counter.most_common() which is most appropriate way for doing this job?
words = input("Enter a line of text: ")
vowels = set("aeiouAEIOU")
x = Counter(c for c in words if c in vowels)
print x.most_common()
Also note that you don't need to use word.upper since you have all the vowels type.And as said in comment you can use set for preserving the vowels which its membership checking complexity is O(1).
So for example, if I input bob, it should give me obb. Likewise, something like plank should give me ankpl.
s = input("What word do you want translated?")
first = s[0]
vowel = "aeiou"
for i in range (1, len(s)):
if first in vowel:
s = s + "way"
print (s)
else:
s = s[1:] + s[0]
print (s)
This currently is only giving me lankp for plank.
Thanks!
It can actually be made much simpler:
s = raw_input("What word do you want translated?").strip()
vowel = set("aeiou")
if vowel & set(s):
while s[0] not in vowel:
s = s[1:] + s[0]
print s
else:
print "Input has no vowels"
You only set first = s[0] once and that is done before the loop. You probably want to set it inside the for loop.
It's probably a little more efficient to search for the vowel and then do the string rotate once:
vowels = 'aeiou'
for index, character in enumerate(s):
if character in vowels: break
s = s[index:] + s[:index]
The problem with your program is that the else isn't indented to the correct level,so you have an for/else construct instead of an if/else.
Here is a more efficient approach.
if vowels = set("aeiou"), you can get the position of the first vowel like this
next(i for i, j in enumerate(s) if j in vowels)
eg:
>>> s = "plank"
>>> vowels = set("aeiou")
>>> next(i for i, j in enumerate(s) if j in vowels)
2
and
>>> s[2:] + s[:2]
'ankpl'
So now you only need to manipulate the string once.
If there are no vowels, the code raises an exception instead of running forever :)
>>> s="why why why?"
>>> next(i for i, j in enumerate(s) if j in vowels)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
This will work
#Move Consonants to the End
def MoveConsonants(input1):
contains_vowel = False
for letter in input1: #Check if the work contains a vowel or not
if letter in 'aeiou':
contains_vowel = True
#If the word doesn't contain a vowel, return the same word
if not contains_vowel:
return input1
#Check if the first letter is a vowel, if so, we can return the string
if input1[0] in 'aeiou':
return input1
#if the first letter is not a vowel, move the first letter to the end and repeat the process
input1 = input1[1:] + input1[0]
return MoveConsonants(input1)
print(MoveConsonants('Plank'))
my code so far, but since i'm so lost it doesn't do anything close to what I want it to do:
vowels = 'a','e','i','o','u','y'
#Consider 'y' as a vowel
input = input("Enter a sentence: ")
words = input.split()
if vowels == words[0]:
print(words)
so for an input like this:
"this is a really weird test"
I want it to only print:
this, is, a, test
because they only contains 1 vowel.
Try this:
vowels = set(('a','e','i','o','u','y'))
def count_vowels(word):
return sum(letter in vowels for letter in word)
my_string = "this is a really weird test"
def get_words(my_string):
for word in my_string.split():
if count_vowels(word) == 1:
print word
Result:
>>> get_words(my_string)
this
is
a
test
Here's another option:
import re
words = 'This sentence contains a bunch of cool words'
for word in words.split():
if len(re.findall('[aeiouy]', word)) == 1:
print word
Output:
This
a
bunch
of
words
You can translate all the vowels to a single vowel and count that vowel:
import string
trans = string.maketrans('aeiouy','aaaaaa')
strs = 'this is a really weird test'
print [word for word in strs.split() if word.translate(trans).count('a') == 1]
>>> s = "this is a really weird test"
>>> [w for w in s.split() if len(w) - len(w.translate(None, "aeiouy")) == 1]
['this', 'is', 'a', 'test']
Not sure if words with no vowels are required. If so, just replace == 1 with < 2
You may use one for-loop to save the sub-strings into the string array if you have checked he next character is a space.
Them for each substring, check if there is only one a,e,i,o,u (vowels) , if yes, add into the another array
aFTER THAT, FROM another array, concat all the strings with spaces and comma
Try this:
vowels = ('a','e','i','o','u','y')
words = [i for i in input('Enter a sentence ').split() if i != '']
interesting = [word for word in words if sum(1 for char in word if char in vowel) == 1]
i found so much nice code here ,and i want to show my ugly one:
v = 'aoeuiy'
o = 'oooooo'
sentence = 'i found so much nice code here'
words = sentence.split()
trans = str.maketrans(v,o)
for word in words:
if not word.translate(trans).count('o') >1:
print(word)
I find your lack of regex disturbing.
Here's a plain regex only solution (ideone):
import re
str = "this is a really weird test"
words = re.findall(r"\b[^aeiouy\W]*[aeiouy][^aeiouy\W]*\b", str)
print(words)