I'm coding this telegram bot for my clan. The bot should send a reply based on a few words in the text msg. Suppose I type a text in the group containing the words "Thalia" and "love" and I want the bot to respond. The following works.
elif "thalia" in text.lower():
if "love" in text.lower():
reply("I love u too babe <3." "\nBut I love my maker even more ;).")
else:
reply("Say my name!")
msg containing thalia and love
I coded it like this because when I use the "and" or "or" keywords the statement doesn't work and the bot goes crazy. In the above, if I code: elif "thalia" and "love"..... it doesn't work.
If there is another way to code this I would appreciate the tip!
Now I am trying the same technique on more words with "and" and "or" but it doesn't work. If I leave "and" and "or" out it works fine. But of course then I can't use the combinations of words I want with this particular response.
elif "what" or "when" in text.lower():
if "time" or "do" in text.lower():
if "match" in text.lower():
reply ("If you need assistence with matches, type or press /matches")
it triggered the command without the 3 words in one sentence
How can I rewrite this code in a more "professional" way and what do I need to change to get it to work? The bot responds only when the combination of the words are used like in the thalia love code. Instead of when "matches" is used.*
Python is much like natural language but the interpreter cannot fill in what human listeners can. 'a and b in c' must be written out as 'a in c and b in c'.
Before writing the if statements, you should lower case text once, not repeatedly. Then turn it into a set of words, after removing punctuation and symbols, to avoid repeated linear searches of the lower-cased string. Here is an incomplete example for ascii-only input.
d = str.maketrans('', '', '.,!') # 3rd arg is chars to delete
text = set(text.lower().translate(d).split())
Your 'matches' snippet can then be written as follows.
elif (("what" in text or "when" in text) and
("time" in text or "do" in text) and
"match" in text)
reply ("If you need assistence with matches, type or press /matches")
You could also use regular expression matching to do the same thing, but logic statements like the above are probably easier to start with.
Related
This is my first time posting so forgive me if it's a little off. I'm having a problem getting my code to index properly. I have to take a sentence and a letter from the user and then state how many times the letter was written in the sentence, while also accounting for upper and lowercase letters
enter image description here
You need to compare userInput[i] with userChar, not userInput, because the string will always be the same whereas with userInput[i] it will give you the current letter.
tho doing:
for letter in userString:
if userChar == letter:
...
if better than
for i in range(len(userString)):
if userChar == userString[i]:
...
Not sure if I clearly describe my question, my original string is:
"1.you are beautiful 2.hello world 3.Thanks!"
I want the output to be:
"1.you are beautiful"
"2.hello world"
"3.Thanks!"
or
"1.you are beautiful
2.hello world
3.Thanks!"
I used split() when the sentence contains comma or period. However, I am thinking if I can write a function by using the number. For example, if type(item)==int then add a line break
Thank you for your help!
Here you go. This will only work for single digit numbers and will work with or without the period.
a='1.you are beautiful 2.hello world 3.Thanks!'
out=''
for ch in a:
if ch.isdigit():
out+='\n'+ch
else:
out+=ch
print(out)
If you want to detect any length number (e.g. 11) you would have to use enumerate(a) and "look ahead" to find the period '.' with another for loop and then add the new line or look into use the re package and Regular Expressions.
I am attempting to limit the character length of my input and then verify whether it is one of the three white characters. Struggling with the final part:
while True:
try:
letter=input("Please enter a character: ") #most intuitive way for me was the assert function but very happy to hear any other ways
assert len(letter) !=1
except AssertionError:
print("Please type only ONE character")
else:
whitespace=["\n"," ","\t"] #i believe the list specification here makes the not in code invalid? believe the two may not be compatible but errors not reached there yet
if whitespace not in letter:
print("Your character in lower case is: "+str(letter).lower())
else:
print("You typed a white space character!")
Welcome to Stackoverflow!
It looks like the error is on the if whitespace not in letter: line. This should actually be the other way around: if item not in list:. You have if list not in item:.
Also, it might help you if I reformat your code a little.
while True:
letter = input('Please enter a character: ')
if len(letter) != 1:
print('Please type only ONE character')
continue
if letter in ['\n', ' ', '\t']:
print("You typed a white space character!")
continue
lowercase_letter = letter.lower()
print(f'Your character in lower case is: {lowercase_letter}')
If you haven't already seen pylint, I'd recommend you take a look at it. It helps you format your code to PEP8 standard. It is also quite good at pointing out some simple errors in your code.
Raising Exceptions are for reporting errors to calling functions - i.e. you can't perform the job the function is supposed to be doing because the input or system state is not as required by the function.
Catching Exceptions is for handling specific errors you know how to handle in a higher level function. So for example, if your trying to read a file and it doesn't exist. In your program that mean the user hasn't set a specific flag in the config file... so you can catch that exception and let the user know how to fix the issue.
Raising an Exception and catching it in the same function (at least in this case) is just a very complicated way of writing an if statement.
When writing an if-else statement, it's a good idea to try and make the if branch positive. Which means avoid if not ...: else: if you can.
In your code, letter is already a string object - so there is no need to create a new string object with str(letter). In python everything is an object, even literals.
The continue statement jumps to the next iteration of the loop. Nothing after the continue is executed in the current iteration of the loop. You could also look at break statement that finishes executing the loop. As an exercise, you could look at adding an extra check to your code to see if the user typed 'quit', and then break. What do you think will happen?
if letter.lower() == 'quit':
break
This would have to be added before the check for single letters otherwise you would never get to this check.
Finally, rather than using string concatenation in your print statement (using str + str). You can use f-strings, format strings as in the example f'Hi my name is {name} and I am from {home}', where name and home are string variables.
Hope this helped!
I'd advise you not to use exceptions because they're very unstable. Instead, I'd use if/else conditions, like this one:
letter = input('Please enter a character: ')
if len(letter) == 1:
if letter in '\n\t ':
print('You typed a white space character!')
else:
print('Your character in lowercase is {}'.format(letter.lower()))
else:
print('Please type only ONE character')```
I have been trying to create a basic program (to later incorporate into a bigger one) that searches for specific words within a user input, here is what I originally did:
command=input(">")
for "hi" in command():
print("Hello there.")
I thought this would search for "hi" in the user input and if it found the word, it would say hi back, this did not work so I tried using variables instead:
command=input(">")
string = "hi"
for string in command():
print("Hello there.")
This still did not work so I did both these again but used "if" instead of "for", and nothing had changed. If anyone could help, it would be much appreciated, thanks! - James.
You need to use in operator for membership checking:
if 'hi' in command:
print("Hello there.")
Also Note that since command is a string and not a callable object you can not use parenthesis the the trailing of it.
And note that when you use in it checks the membership in the whole of the string and it's possible that you have another word in your text which is contains hi like high, that using in it will returns True which is not what you want.
So all you should do is splitting the string with whitespaces and check the membership of word hi within other words:
if 'hi' in command.split():
print("Hello there.")
I don't know yahoo pipes so much, i am just wandering, is it possible to make the first word moved to be the last word of sentence ?
for example, i got some feed, with an item title like this
Stackoverflow : The best way to do self-programming learning
then i want to move the first word, which is Stackoverflow to be the last word like this
The best way to do self-programming learning - Stackoverflow
how do i do that ?
in my logic :
we need to separate the first words from the feeds, then store them into "memory" or some kind like that"
then we use string builder then take the stored words to the last sentence. but i don't know 'the tools' that works like "memory" or some kind like that
updates :
how do i join both string regex loops into 1 items ?
The pipes themselves will serve as memory. :-)
a) create a regex operator stripping the colon and everything in front.
b) create a regex operator stripping the colon and everything after.
c) pass the string to both a) and b).
d) create a string builder for [input-from-a] + " - " + [input-from-b].
Tried sharing an example here: http://pipes.yahoo.com/pipes/pipe.info?_id=68b135e6b9a182a8bf9e1f329eaaf6f5