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).
Related
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
Specifically, a user inputs a word. I want to compile a list of all the vowels and consonants used (no repeats, just a note of each one that is used). However, I only want to begin counting consonants AFTER the last vowel in the word is found.
For example, if the input is "hello", it should count e,o, but no consonants, as there are non after the last vowel, with a count vowels=2, consonants=0. If the input is "swarm" it should count a, r, m, vowels=1, consonants=2. "Book" would give you o,k,vowels=1, consonants=1.
There are other conditions I'd like the program to meet, but this one is the first step, and the most important to begin with.
Here's what I have, but it is not working as I need it to (as there is a line for each letter of the alphabet, I will just use quotation marks to show the continuation of the statements):
for i, ch in enumerate(word):
if ch in VOWELS:
if ch=="a" and ch not in VL:
VL=VL+"a"
VC+=1
if ch=="e" and ch not in VL:
VL=VL+"e"
VC+=1
#" " for each other vowel
if ch not in VOWELS:
if ch=="b" and ch not in CL:
CL=CL+"b"
CC+=1
if ch=="c" and ch not in CL:
CL=CL+"c"
CC+=1
#" " for each other consonant
print(VL[1:])
print(VC)
print(CL[1:])
print(CC)
I've tried indenting the consonant section to only begin after the vowel search is done, however, that does not seem to work. I need to index the location of the last vowel, and then start the consonant loop.
As a side not, we're only doing pretty basic commands, such as Boolean, concatenation, and string methods. No dictionaries or lists or things like that. I'm pretty sure there is a simple way to do this, but I can't seem to figure it out.
Instead of only counting consonents after the first vowel, why don't you count every time, but reset the results whenever you find a vowel?
if ch=="a" and ch not in VL:
VL=VL+"a"
VC+=1
CL = "" # add these two lines to each condition
CC = 0
And since I can't resist, the code can be made much shorter and more efficient:
VL = set()
CL = set()
for ch in word:
if ch in VOWELS:
VL.add(ch)
CL = set()
else:
CL.add(ch)
VC = len(VL)
CC = len(CL)
While you're looping over the word, you can also use your i value to loop backwards through its characters. Then, we use a boolean to determine whether our backwards search has hit a vowel yet or not, and only count consonants before the first vowel is hit:
vowels = 'aeiou'
VL=''
VC=0
CL=''
CC=0
word = 'hello'
count_cons = True
for i, c in enumerate(word):
if c in vowels and c not in VL:
VL += c
VC += 1
if word[-i-1] in vowels:
count_cons = False
elif count_cons:
CL += word[-i-1]
CC += 1
print(VL)
print(VC)
print(CL)
print(CC)
This prints:
eo
2
0
If you wanted to shorten this down, you could do something like:
VL = set(c for c in word if c in vowels)
CL = set(c for i, c in enumerate(word)
if c not in vowels and all(x not in vowels for x in word[i+1:]))
VC = len(VL)
CC = len(CL)
print(VL)
print(CL)
print(VC)
print(CC)
print ("Sentence analysis")
Sentence = (input("Please enter a sentence"))
def WordCount(Sentence):
words = (Sentence.count(' ')+1)
print ("There are", words ,"words in this sentence")
WordCount(Sentence)
The code above is fine and used to count how many words in the input sentence.
vowels = ['a','e','i','o','u']
count=0
for v in vowels:
if v in Sentence:
count+=1
print (count)
When running, say if I input a a e i o u would only count 5 vowels whereas there are 6. How do I fix this?
Use .count():
count = 0
for v in vowels:
count += Sentence.count(v)
Or better:
count = sum(Sentence.count(v) for v in vowels)
That is because you are doing your check in reverse. You want to go over your sentence and check each letter against vowels:
vowels = ['a','e','i','o','u']
count=0
for s in Sentence:
if s in vowels:
count+=1
print (count)
For a nicer approach, however, check out #zondo's answer.
The problem you are having is that when you loop through v in vowels and check if v is in Sentence it only checks if it v is present in Sentance not how many times. If you flip it around so it checks through Sentence first and check each letter to see if it is in vowels it will check all of the letters in Sentence.
print ("Sentence analysis")
Sentence = (input("Please enter a sentence"))
vowels = ['a','e','i','o','u']
count=0
for letter in Sentence:
if letter in vowels:
count+=1
print (count)
For the first code can be simplified the WordCount() function as:
print(len(Sentence.split()))
or:
import re
print(len(re.findall(r'\w+', Sentence)))
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))
I would like to compare the input letters(dictionary) with the list(textfile with words) and print the words matching the inputed letters. What have I done wrong?(I know i only have a print YES or NO-function if it finds a matching word at the moment. What's the best way to create this function by the way?).
def ordlista(list):
fil = open("ord.txt", "r")
words = fil.readlines()
list = []
for w in words:
w = w.strip()
list.append(w)
return list
chars = {}
word = raw_input("Write 9 letters: ")
for w in word:
w = w.lower()
if w not in chars:
chars[w] = 1
else:
chars[w] += 1
if chars.keys() in ordlista(list):
print "YES"
else:
print "NO"
chars.keys() is a list, so
chars.keys() in ordlista(list):
will never be True. What you want is match the letter counts against each word in your list. So I'd suggest
charsum = sum(chars.values())
for word in wordlist:
if len(word) == charsum and all([(word.count(c) == chars[c]) for c in chars]):
print "YES for word '%s'" % word
EDIT: If you want those words to match which have at least the letter counts (i.e. a word with 3 a's will match an input of two a's), then you'll have to change the == to a >=.
EDIT2: Since you want exact matches, the easiest solution would be to count the number of chars and make sure the word has that length.
You are checking for the presence of the entire list of keys in your character list, rather than checking for each key individually. You must iterate over your keys individually, and then check for their presence.
for k in chars:
if k in ordlista(list):
print "YES"
else:
print "NO"
If you want to print the words which consist solely of the letters in your character list, you may use the following approach.
for word in ordlista(list):
if not filter(lambda char: char not in chars, word):
print word
Use sets:
chars = set(raw_input("Write 9 letters: "))
for word in ordlista(None):
if(set(word) == chars):
print "YES for '%s'" % word
BTW, the argument list to ordlista is unnecessary, as it is not used. I would also advise against using the name list in general, because it hides the built-in <type 'list'>
Update: I have read your comment on jellybean's post. If every letter can only be used once, you can obviously not use sets!