How do I print words with only 1 vowel? - python

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)

Related

How do I print out individual words within my list?

I am trying to print each word from my list onto separate lines, however it is printing each letter onto individual lines
Words = sentence.strip()
for word in sentence:
print (word)
My full code (for anyone wondering) is:
import csv
file = open("Task2.csv", "w")
sentence = input("Please enter a sentence: ")
Words = sentence.strip()
for word in sentence:
print (word)
for s in Words:
Positions = Words.index(s)+1
file.write(str(Words) + (str(Positions) + "\n"))
file.close()
You forgot to split sentence and use "Words" not "sentence" in first for loop.
#file = open("Task2.csv", "w")
sentence = input("Please enter a sentence: ")
Words = sentence.split()
for word in Words:
print (word)
for s in Words:
Positions = Words.index(s)+1
#file.write(str(Words) + (str(Positions) + "\n"))
#file.close()
Output:
C:\Users\dinesh_pundkar\Desktop>python c.py
Please enter a sentence: I am Dinesh
I
am
Dinesh
C:\Users\dinesh_pundkar\Desktop>
You need to used str.split() instead of str.strip().
str.strip() only removes the leading and trailing whitespaces in a string:
>>> my_string = ' This is a sentence. '
>>> my_string.strip()
'This is a sentence.'
str.split() does what you want which is return a list of the words in the string; by default, using whitespace as the delimiter string:
>>> my_string = ' This is a sentence. '
>>> my_string.split()
['This', 'is', 'a', 'sentence.']
So, your code should look more like:
words = sentence.split()
for word in sentence:
print(word)

How to use .split, enumerate and lists to find positions of a word in a sentence

I have been asked to find the position(s) of an input word from an input sentence and I am having trouble figuring out how to use enumerate, .split and lists together. This is what I have so far:
sntc=str(input("Please input a sentence with no punctuation."))
wrd=str(input("Please input a word from that sentence."))
words=sntc.split
list(enumerate(sntc))
for x in y in enumerate:
if x==(wrd):
print ("The chosen word is in postion(s):",x+1)
You don't need to convert input to a str. It's already a string.
words isn't what you think it is. All that is is a reference to the split method. You never actually call the method split.
e.g. -
>>> a_string = "Look a string"
>>> print(a_string.split)
>>> <built-in method split of str object at (memory address)>
Whereas calling split, we have:
>>> print(a_string.split())
>>> ['Look', 'a', 'string']
It's unclear what exactly you're trying to achieve with enumerate and everything below words = sntc.split. I think you actually want to split sntc enumerate over it and check if the given wrd matches an item in this split list.
There's another problem, enumerate returns the index in the iterable and the item in the iterable, the index (position) here will just be the position in this list (words) + 1.
Not the actual position in the sentence.
e.g. -
>>> sntc = input("Please input a sentence with no punctuation: ")
Please input a sentence with no punctuation: Look a sentence
>>> wrd = input("Please input a word from that sentence: ")
Please input a word from that sentence: a
>>> words = sntc.split()
Words = ['Look', 'a', 'sentence']. Position of 'a' is 1 here.
>>> for i, word in enumerate(words):
... if word == wrd:
... print("Chosen word is in position %d" % (i + 1))
...
Chosen word is in position 2 #Position of 'a' + 1
What you actually want is:
for word in words:
if word == wrd:
print("Position is %d" % sntc.index(word))
This is a solution you're looking for - simple and efficient:
sntc = input("Please input a sentence with no punctuation. ")
wrd = input("Please input a word from that sentence. ")
words = sntc.split()
print(words.index(wrd) + 1)
Using enumerate and lists:
sntc = input("Please input a sentence with no punctuation. ")
wrd = input("Please input a word from that sentence. ")
words = sntc.split()
e = list(enumerate(sntc))
for ind, word1 in e:
if word1 == wrd:
print("The chosen word is in postion(s):", ind+1)
Your code doesn't work for a few reasons:
1) If you want to assign a return value of a function to a variable, call the function to get that return value and not the function itself:
>>> words = sntc.split
>>> words # the variable words now contains a function
<built-in method split of str object at 0x0243F4D0>
>>> words = sntc.split()
>>> words # and now a list that you want
['text', 'text', 'text']
2) You can't iterate over enumerate, as it's a function and not an iterable
You didn't assign the list(enumerate(sntc)) to any variable, and I'm pretty sure you meant to iterate over that:
e = list(enumerate(sntc)) # now you can iterate over e
for ind, word in e:
print(ind, word)
if you want the position of an element in a list use listname.index()
a = ["hello", "world"]
a.index("hello")
returns 0
The following approach helps you to use .split, enumerate and lists to find positions of a word in a sentence.
sentence = 'I like movie' # given sentence
sentence = sentence.split() # spliting sentence to split
wrd = 'like' # a given word to find position in the sentence
[i for i, w in enumerate(sentence) if w==wrd]

How to find the position of a repeating word in a string - Python

How to get Python to return the position of a repeating word in a string?
E.g. the word "cat" in "the cat sat on the mat which was below the cat" is in the 2nd and 11th position in the sentence.
You can use re.finditer to find all occurrences of the word in a string and starting indexes:
import re
for word in set(sentence.split()):
indexes = [w.start() for w in re.finditer(word, sentence)]
print(word, len(indexes), indexes)
And using dictionary comprehension:
{word: [w.start() for w in re.finditer(word, sentence)] for word in sentence.split()}
This will return a dictionary mapping each word in the sentence, which repeates at least once, to the list of word index (not character index)
from collections import defaultdict
sentence = "the cat sat on the mat which was below the cat"
def foo(mystr):
sentence = mystr.lower().split()
counter = defaultdict(list)
for i in range(len(sentence)):
counter[sentence[i]].append(i+1)
new_dict = {}
for k, v in counter.iteritems():
if len(v) > 1:
new_dict[k] = v
return new_dict
print foo(sentence)
The following will take an input sentence, take a word from the sentence, and then print the position(s) of the word in a list with a starting index of 1 (it looks like that's what you want from your code).
sentence = input("Enter a sentence, ").lower()
word = input("Enter a word from the sentence, ").lower()
words = sentence.split(' ')
positions = [ i+1 for i,w in enumerate(words) if w == word ]
print(positions)
I prefer simplicity and here is my code below:
sentence = input("Enter a sentence, ").lower()
word_to_find = input("Enter a word from the sentence, ").lower()
words = sentence.split() ## Splits the string 'sentence' and returns a list of words in it. Split() method splits on default delimiters.
for pos in range(len(words)):
if word_to_find == words[pos]: ## words[pos] corresponds to the word present in the 'words' list at 'pos' index position.
print (pos+1)
The 'words' consists of the list of all the words present in the sentence. Then after that, we iterate and match each word present at index 'pos' with the word we are looking to find(word_to_find) and if both the words are same then we print the value of pos with 1 added to it.
Hope this is simple enough for you to understand and it serves your purpose.
If you wish to use a list comprehension for the above, then:
words = sentence.split()
positions = [ i+1 for i in range(len(words)) if word_to_find == words[i]]
print (positions)
Both the above ways are same, just the later gives you a list.
positions= []
sentence= input("Enter the sentence please: ").lower()
sentence=sentence.split( )
length=len(sentence))
word = input("Enter the word that you would like to search for please: ").lower()
if word not in sentence:
print ("Error, '"+word+"' is not in this sentence.")
else:
for x in range(0,length):
if sentence[x]==word: #
positions.append(x+1)
print(word,"is at positions", positions)
s="hello fattie i'm a fattie too"
#this code is unsure but manageable
looking word= "fattie"
li=[]
for i in range(len(s)):
if s.startswith(lw, i):
print (i)
space = s[:i].count(" ")
hello = space+1
print (hello)
li.append(hello)
print(li)

In python, how do I find the vowels in a word?

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))

Python: How to print a word one letter at a time

How do I use Python to print a word one letter at a time? Any help would be appreciated.
If i understood you correctly than you can use the following code:
for word in text.split():
print word
else if you need to print word's letters:
for let in word:
print let
In case you need to skip punctuation and so on you can also use regEx:
tst = 'word1, word2 word3;'
from re import findall
print findall(r'\w+', tst)
Or not very pythonic:
skipC = [':','.', ',', ';']# add any if needed
text= 'word1, word2. word3;'
for x in skipC:
text = text.replace(x, ' ')
for word in text.split():
print word

Categories

Resources