I am creating a random sentence generator that can apply the
correct indefinite article (a, an) to the sentence.
But I am getting results such as these:
I eat a apple. I ride an bike. You eat an apple.
"a" should come before the consonant, and "an" should come before the vowel: an apple; a bike.
What am I doing wrong?
Import random
def main():
pronoun = ["I ", "You "]
verb = ["kick ", "ride", "eat "]
noun = [" ball.", " bike.", " apple.", " elephant."]
ind_art = "an" if random.choice(noun[0]).lower() in "aeiou" else "a"
a = random.choice(pronoun)
b = random.choice(verb)
c = ind_art
d = random.choice(noun)
print(a+b+c+d)
main()
When you call random.choice it returns a new value each time. So the random word in the line where you create your ind_art is a different word from the one that gets assigned to d.
You need to reorder your code so that d is used when determining the article.
d = random.choice(noun)
ind_art = "an" if d[0].lower() in "aeiou" else "a"
I fixed some lines in your code. Now, it works fine.
import random
def main():
pronoun = ["I ", "You "]
verb = ["kick ", "ride ", "eat "]
noun = ["ball.", "bike.", "apple.", "elephant."]
ch = random.choice(noun).lower() # <===== fixed this line
# print(ch[0]) # test
ind_art = "an " if ch[0] in "aeiou" else "a " # <===== fixed this line
a = random.choice(pronoun)
b = random.choice(verb)
c = ind_art
# d = random.choice(noun) # <===== removed this line
print(a+b+c+ch) # <===== replaced d with ch
main()
Related
from emot.emo_unicode import UNICODE_EMOJI
tweet = "#homer #yolo good hello๐๐bye evening :-) and :) you should've"
def add_spaces(tweet):
words = tweet.split()
print(words)
for i, w in enumerate(words):
for emot in UNICODE_EMOJI:
if w == emot:
words[i] = " " + w + " "
new_tweet = " ".join(words)
print(new_tweet)
result = add_spaces(tweet)
print(result)
With the function above i try to make spaces, but only between the emojis and the word before und behind. So the output should be:
#homer #yolo good hello ๐ ๐ bye evening :-) and :) you should've
when i run this function i get the following output:
for new_tweet = #homer #yolo good hello๐๐bye evening :-) and :) you should've
for result = None
you see the new_tweet is the same as tweet. I hope somebody can tell me where i made a mistake.
fyi: i also tried it with this function:
def add_spaces(s):
# split the string into a list of words, emojis, and punctuation
words = re.findall(
r"(?:[\wโ]+[\w']+|(?:[\U0001f300-\U0001f64f])|(?:[\U0001f680-\U0001f6ff])|(?:[\.,!?:;.##)(]))",
s,
)
# loop through each word in the list
for i, w in enumerate(words):
# check if the word is an emoji
if w.startswith("\\U") and not w.startwith("#"):
# add a space before and after the emoji
words[i] = " " + w + " "
# check if the word is an "#" symbol
elif w == "#":
# do not add a space after the "#" symbol
words[i] = w
# join the words back together
s = " ".join(words)
return s
This function works... BUT:
it also makes space between the # and the #
So the output here is:
# homer # yolo good hello ๐ ๐ bye evening : ) and : ) you should've
The program recognizes the # and the # also as some kind of emoji. Maybe it is some kind of encoding problem?!
i hope somebody can give me some nice advices to make this function work. ty :)
lets say when the program starts, the user is printed a line where he/she can input
values Eg:
I have apples and I have pears
and then the user can input values in both spaces, after both "have"
A basic program to do this would be
input1 = input("Enter a fruit ") #Ask the user to input
input2 = input("Enter another fruit") #then ask for another
str = "I have a(n) " #store the basic string (the 'n' is in brackets because we don't know if the user input will start with a vowel or not .. you can develop this later)
str = str + input_string1 + " and" + str + input_string2 #concatenate the lot
print("Output = ", str) #this will give you "Output = "(your sentence)
print(str) #or you could just print the string
Hope this helps
(this is code for, alternatively, accepting a list/splitting/using a for loop, but you would have to add more code to check for adding " and", checking for vowels etc..)
input_string = input("Enter fruits separated by a comma ")
str = "I have a(n) "
fruit_list = input_string.split(",")
#print out the result
for fruit in fruit_list:
print(str + fruit )
I'm working on a small program which takes a text input - and then places each of these items in a dictionary alongside which line they were entered on. At the moment if I enter 4 lines of text. It'll take them all out correctly, but every word will be set to the value 4 - instead of the loop it was inputted on. I've removed all the other functions from my code (remove punct, remove stopwords, stemwords, etc). to make this clearer.
from string import *
function = False
words_split = []
lineNumber=0
final_value = []
def indexer(t):
global words_split
words = t.split();
for word in words:
words_split.append(word)
def dict_print():
for keys in Dict:
output = keys + " " + str(Dict[keys][0])
i= 1
while i < len(Dict[keys]):
output = output + ", " + str(Dict[keys][i])
i = i + 1
print(output)
print("Please type a line and hit 'Enter' or type a single fullstop followed by 'Enter' to exit \n")
text = ""
while function == False :
if(text == "."):
print("The index is:")
function = True
dict_print()
else:
Dict = {}
text = input()
lineNumber += 1
for word in words_split:
if word in Dict:
if lineNumber not in Dict[word]:
Dict[word] = Dict[word] + [lineNumber]
else:
Dict[word] = [lineNumber]
indexer(text)
My global variable was causing the issue. I'll leave this up with my completed full code in case someone else runs into the same issue (:
https://repl.it/#Glaschu/AdmiredSteelCardinal
I'm trying to reverse the words in a string individually so the words are still in order however just reversed such as "hi my name is" with output "ih ym eman si" however the whole string gets flipped
r = 0
def readReverse(): #creates the function
start = default_timer() #initiates a timer
r = len(n.split()) #n is the users input
if len(n) == 0:
return n
else:
return n[0] + readReverse(n[::-1])
duration = default_timer() - start
print(str(r) + " with a runtime of " + str(duration))
print(readReverse(n))
First split the string into words, punctuation and whitespace with a regular expression similar to this. Then you can use a generator expression to reverse each word individually and finally join them together with str.join.
import re
text = "Hello, I'm a string!"
split_text = re.findall(r"[\w']+|[^\w]", text)
reversed_text = ''.join(word[::-1] for word in split_text)
print(reversed_text)
Output:
olleH, m'I a gnirts!
If you want to ignore the punctuation you can omit the regular expression and just split the string:
text = "Hello, I'm a string!"
reversed_text = ' '.join(word[::-1] for word in text.split())
However, the commas, exclamation marks, etc. will then be a part of the words.
,olleH m'I a !gnirts
Here's the recursive version:
def read_reverse(text):
idx = text.find(' ') # Find index of next space character.
if idx == -1: # No more spaces left.
return text[::-1]
else: # Split off the first word and reverse it and recurse.
return text[:idx][::-1] + ' ' + read_reverse(text[idx+1:])
I want to print out all words in a string, line by line without using split() funcion in Python 3.
The phrase is a str(input) by the user, and it has to print all the words in the string, no matter it's size.Here's my code:
my_string = str(input("Phrase: "))
tam = len(my_string)
s = my_string
ch = " "
cont = 0
for i, letter in enumerate(s):
if letter == ch:
#print(i)
print(my_string[cont:i])
cont+=i+1
The output to this is:
Phrase: Hello there my friend
Hello
there
It is printing only two words in the string, and I need it to print all the words , line by line.
My apologies, if this isn't a homework question, but I will leave you to figure out the why.
a = "Hello there my friend"
b = "".join([[i, "\n"][i == " "] for i in a])
print(b)
Hello
there
my
friend
Some variants you can add to the process which you can't get easily with if-else syntax:
print(b.Title()) # b.lower() or b.upper()
Hello
There
My
Friend
def break_words(x):
x = x + " " #the extra space after x is nessesary for more than two word strings
strng = ""
for i in x: #iterate through the string
if i != " ": #if char is not a space
strng = strng+i #assign it to another string
else:
print(strng) #print that new string
strng = "" #reset new string
break_words("hell o world")
output:
hell
o
world