I made a really simple program that requests an input and puts a comma or question mark at the end. If the sentence starts with why, how, etc, the program adds an question mark.
But how can I make the last comma a period, so that I can make a proper sentence?
The code:
def sentence_maker(phrase):
x = ("Why", "What", "Who", "How")
sentence = phrase.capitalize()
if sentence.startswith(x):
return "{}?\n".format(sentence)
else:
return "{},".format(sentence)
results = []
while True:
y = input("Say something: ")
if y=="end":
break
else:
results.append(sentence_maker(y))
print(" " .join(results))
The idea is to make something that work like this:
input:
say something: hello
say something: how are you
say something: i'am good
say something: thank you
output:
Hello, How are you?
I'am good, Thank you.
One way to fix this could be to edit the last element after registering that the input is "end".
while True:
y = input("Say something: ")
if y=="end":
results[-1] = results[-1][:-1] + "."
break
else:
results.append(sentence_maker(y))
Test Output:
Say something: Why
Say something: the
Say something: quick
Say something: brown
Say something: fox
Say something: jumps
Say something: end
Why?
The, Quick, Brown, Fox, Jumps.
Related
I have been searching for the solution to this problem. I am writing a custom function to count number of sentences. I tried nltk and textstat for this problem but both are giving me different counts.
An Example of a sentence is something like this.
Annie said, "Are you sure? How is it possible? you are joking, right?"
NLTK is giving me --> count=3.
['Annie said, "Are you sure?', 'How is it possible?', 'you are
joking, right?"']
another example:
Annie said, "It will work like this! you need to go and confront your
friend. Okay!"
NLTK is giving me --> count=3.
Please suggest. The expected count is 1 as it is a single direct sentence.
I have written a simple function that does what you want:
def sentences_counter(text: str):
end_of_sentence = ".?!…"
# complete with whatever end of a sentence punctuation mark I might have forgotten
# you might for instance want to add '\n'.
sentences_count = 0
sentences = []
inside_a_quote = False
start_of_sentence = 0
last_end_of_sentence = -2
for i, char in enumerate(text):
# quote management, to solve your issue
if char == '"':
inside_a_quote = not inside_a_quote
if not inside_a_quote and text[i-1] in end_of_sentence: # 🚩
last_end_of_sentence = i # 🚩
elif inside_a_quote:
continue
# basic management of sentences with the punctuation marks in `end_of_sentence`
if char in end_of_sentence:
last_end_of_sentence = i
elif last_end_of_sentence == i-1:
sentences.append(text[start_of_sentence:i].strip())
sentences_count += 1
start_of_sentence = i
# same as the last block in case there is no end punctuation mark in the text
last_sentence = text[start_of_sentence:]
if last_sentence:
sentences.append(last_sentence.strip())
sentences_count += 1
return sentences_count, sentences
Consider the following:
text = '''Annie said, "Are you sure? How is it possible? you are joking, right?" No, I'm not... I thought you were'''
To generalize your problem a bit, I added 2 more sentences, one with ellipsis and the last one without even any end punctuation mark. Now, if I execute this:
sentences_count, sentences = sentences_counter(text)
print(f'{sentences_count} sentences detected.')
print(f'The detected sentences are: {sentences}')
I obtain this:
3 sentences detected.
The detected sentences are: ['Annie said, "Are you sure? How is it possible? you are joking, right?"', "No, I'm not...", 'I thought you were']
I think it works fine.
Note: Please consider the quote management of my solution works for American style quotes, where the end punctuation mark of the sentence can be inside of the quote. Remove the lines where I have put flag emojis 🚩 to disable this.
So I want to make a bot that tells jokes but I am having trouble checking if any part of an input is part of a seperate list. So for instance (side note: this is all in a while loop):
punWords = [pun, Puns]
userInput = input('What kind of jokes do you want to hear?')
elif userInput in punWords:
print(random.choice(punJokes))
print(random.choice(jokeResponses))
print(' ')
jokeFunc2()
else:
print('Sorry I dont know any of these jokes')
The problem im having is that if the user inputs something like "I want to hear a pun" Then it goes through and compares every word to punWords and if it doesn't match then it prints the "Sorry I don't know any of these jokes" message so that the output ends up looking something like this:
'Sorry I dont know any of these jokes'
'Sorry I dont know any of these jokes'
'Sorry I dont know any of these jokes'
'Sorry I dont know any of these jokes'
'Sorry I dont know any of these jokes'
'Insert pun joke'
What I want to happen is that it only prints the error message if the input doesnt match any of the other words. Thanks a lot for any help and sorry if the post isnt done right (this is my first time posting on any kind of forum).
One way you could do it is to count the number of matches. Then if there are zero matches, print the error message. Something like:
if userInput in punWords:
matchedWords += 1
then after the while loop
if matchedWords:
# do your thing
else:
print ("Sorry I don't know any of these jokes")
You are basically looking for the intersection between two lists (the list of pun words and the list of words entered), which can be performed using a Python set:
words = userInput.split()
if (set(words) & set(punWords)):
print(random.choice(punJokes))
or more simply demonstrated:
a = [1,2,3]
b = [3,4,5]
print(list(set(a) & set(b))) #result: [3]
For example
userDay = input("How was you day? ")
The user input "My day was good"
and then the program recognizes that the user said "good", and then chooses the correct response for "good".
Sorry if you don't understand, its hard to explain.
Easy and quick way would be split the response into words using response.split() and then check each word if it equal to good
This way you can avoid searching for ‘ good’ or ‘ good ‘ or ’good ‘ (good word can be starting word, ending word or somewhere in the line)
I'd suggest using python's built-in lexical analysis tool, shlex. It is very useful as it contains functionality that makes it easy to write a (simple) lexical analyzer.
So in your case you can do something like this:
import shlex
user_input = 'My day was good'
li = shlex.split(user_input)
print 'Your day was good' if 'good' in li else 'Your day was bad'
The prints here are for demonstrating purposes only. You have to substitute them with your code that will choose the correct response for "good".
Just check if a substring is in a string:
userDay = input("How was you day? ")
if 'good' in userDay:
print('good')
or you can use:
if userDay.find('good') == 1:
print('good')
Something like this:
response = input("How was you day? ")
if response == 'good':
# do something
Or if you're just looking for 'good' in the response somewhere:
response = input("How was you day? ")
if 'good' in response.lower():
# do something
class Song(object):
def __init__(self, lyrics):
self.lyrics = lyrics
def sing_me_a_song(self):
for line in self.lyrics:
print line
cheese = "Happy birthday to you,\nI dont want to get sued,\nSo I'll stop right there"
bulls_on_parade = Song(["They rally around tha family",
"With pockets full of shells"])
Song([cheese]).sing_me_a_song()
bulls_on_parade.sing_me_a_song()
Here I'm talking about the Song([cheese]).sing_me_a_song() I made.
If I enter it as song(cheese).sing_me_a_song()
t
h
i
s
h
a
p
p
e
n
s
However if I put brackets like this song([cheese)].sing_me_a_song it is fixed.
What causes this? Is the brackets related to a list
Strings are iterable, just like lists are. You are passing in a single string, which can be iterated. However, when iterating over a string, you get each individual character, which is why you get your output:
>>> cheese = "Happy birthday to you,\nI dont want to get sued,\nSo I'll stop right there"
>>> for i in cheese[:5]: # first 5 characters
... print i
...
H
a
p
p
y
If you expected there to be separate lines, then create a list with those lines:
cheese = ['Happy birthday to you,', 'I dont want to get sued,', "So I'll stop right there"]
or have Python create the list from the string using the str.splitlines() method:
>>> cheese = "Happy birthday to you,\nI dont want to get sued,\nSo I'll stop right there"
>>> cheese.splitlines()
['Happy birthday to you,', 'I dont want to get sued,', "So I'll stop right there"]
e.g. pass the latter to your song() class:
song(cheese.splitlines()).sing_me_a_song()
I have a series of strings, and I want Python to take it sentence by sentence when creating a tuple. For example:
string = [("I am a good boy"), ("I am a good girl")]
tuple = [("I am a good boy", -1), ("I am a good girl", -1)]
But apparently it's doing:
tuple = [("I", -1), ("am", -1), ("a", -1), ("good", -1), ("boy", -1).....]
What went wrong and how do I resolve it?
import re
def cleanedthings(trainset):
cleanedtrain = []
specialch = "!##$%^&*-=_+:;\".,/?`~][}{|)("
for line in trainset:
for word in line.split():
lowword = word.lower()
for ch in specialch:
if ch in lowword:
lowword = lowword.replace(ch,"")
if len(lowword) >= 3:
cleanedtrain.append(lowword)
return cleanedtrain
poslinesTrain = [('I just wanted to drop you a note to let you know how happy I am with my cabinet'), ('The end result is a truly amazing transformation!'), ('Who can I thank for this?'), ('For without his artistry and craftmanship this transformation would not have been possible.')]
neglinesTrain = [('I have no family and no friends, very little food, no viable job and very poor future prospects.'), ('I have therefore decided that there is no further point in continuing my life.'), ('It is my intention to drive to a secluded area, near my home, feed the car exhaust into the car, take some sleeping pills and use the remaining gas in the car to end my life.')]
poslinesTest = [('Another excellent resource from Teacher\'s Clubhouse!'), ('This cake tastes awesome! It\'s almost like I\'m in heaven already oh God!'), ('Don\'t worry too much, I\'ll always be here for you when you need me. We will be playing games or watching movies together everytime to get your mind off things!'), ('Hey, this is just a simple note for you to tell you that you\'re such a great friend to be around. You\'re always being the listening ear to us, and giving us good advices. Thanks!')]
neglinesTest = [('Mum, I could write you for days, but I know nothing would actually make a difference to you.'), ('You are much too ignorant and self-concerned to even attempt to listen or understand. Everyone knows that.'), ('If I were, your BITCHY comments that I\'m assuming were your attempt to help, wouldn\'t have.'), ('If I have stayed another minute I would have painted the walls and stained the carpets with my blood, so you could clean it up... I wish I were never born.')]
clpostrain = cleanedthings(poslinesTrain)
clnegtrain = cleanedthings(neglinesTrain)
clpostest = cleanedthings(poslinesTest)
clnegtest = cleanedthings(neglinesTest)
trainset= [(x,1) for x in clpostrain] + [(x,-1) for x in clnegtrain]
testset= [(x,1) for x in clpostest] + [(x,-1) for x in clnegtest]
print testset
You joined the final result by words instead by sentences. Adding a variable for every sentence will fix your error
def cleanedthings(trainset):
cleanedtrain = []
specialch = "!##$%^&*-=_+:;\".,/?`~][}{|)("
for line in trainset:
#will append the clean word of the current sentence in this var
sentence = []
for word in line.split():
lowword = word.lower()
for ch in specialch:
if ch in lowword:
lowword = lowword.replace(ch,"")
if len(lowword) >= 3:
sentence.append(lowword)
#once we check all words, recreate the sentence joining by white space
#and append to the list of cleaned sentences
cleanedtrain.append(' '.join(sentence))
return cleanedtrain