say_d = ["say", "tell me"]
a = input("Please Type An Action For Me To Do: ")
if any(word in a for word in say_d):
print(a)
This is the program that prints out the typed input, if any keyword from say_d is in it. But it will also print the keyword. Is there any way to remove the keyword from the supposed output? Like:
say_d = ["say", "tell me"]
a = input("Please Type An Action For Me To Do: ")
if any(word in a for word in say_d):
print(a-say_d)
You can use either regex or str.replace to replace the common words with empty string:
import re
say_d = ["say","tell me"]
a = (input("Please Type An Action For Me To Do: "))
if any(word in a for word in say_d):
print(re.sub('|\b'.join(say_d), '', a))
But Note that if you want to remove the common words if thery exist in input, you don't need to use any, for both functions (re.sub and str.replace) replace the string only of they exist in your text.
Also, the part word in a will check the membership within the entire input string, not its words. That says, if one of the words within the input string is contain a word inside say_d it will return True. Like sayulita which is contain the word say.
For getting ride of this problem you can again check the membership by splitting the input string and then looping over it or use regex.
This is what you looking for:
say_d=["say","tell me"]
a=(input("Please Type An Action For Me To Do: "))
if any(word in a for word in say_d):
set2 = set(say_d)
result = [element for element in a if element not in set2]
print(list(result))
Without any input and output in question, i assume that you want to remove any candidate word(which in list say_d) from input string, so maybe it can be as simple as below:
say_d=["say","tell me"]
a=(input("Please Type An Action For Me To Do: "))
ret = reduce(lambda r, w: r.replace(w, ''), say_d, a)
if len(ret) != len(a):
print ret
Related
As a foreword, I'm quite new to python, and coding in general.
I'm trying to get the following code to find the specific values in the foodgroups tuple that match with user input (ie: Dairy, Nuts, and Grain) and attach them to Output (ie: Dairy and Nuts). The line with Output was gotten from another website when I was first making this. The code works when the user provides an input that only contains one item without any symbols or spaces (ie: Dairy) but anything extra causes Output to be blank when printed.
userinput = input("Enter foodgroups ate in the last 24hrs : ").title()
foodgroups = ("Dairy","Nuts","Seafood","Chocolate")
Output = list(filter(lambda x:userinput in x, foodgroups))
if foodgroups[0] or foodgroups[1] or foodgroups[2] or foodgroups[3] in userinput:
print(Output,"is present in your list, " + userinput)
else:
print("Negative.")
I've thought of swapping around foodgroups and userinput, but that results in a TypeError, and turning the tuple into a string has Output always return blank.
I've asked others how to fix this, but they've had no better luck. Any help is appreciated!
If userinput is a comma separated string then split it and use a list:
userinput = input("Enter foodgroups ate in the last 24hrs : ")
foodgroups = ("Dairy","Nuts","Seafood","Chocolate")
uin = userinput.split(",")
grp = []
for x in uin:
if x in foodgroups:
grp.append(x)
grp is the user defined foods in foodsgroup
The main thing is that you want to use split to separate individual words from the user input into a list of words. I also swapped x and seafoods in your lambda.
If the user separates each word by one or more spaces, here's how to change your code to work:
userinput = input("Enter foodgroups ate in the last 24hrs : ").title()
foodgroups = ("Dairy","Nuts","Seafood","Chocolate")
userfoods = userinput.split()
Output = list(filter(lambda x: x in userfoods, foodgroups))
print(Output,"is present in your list, " + str(userinput))
As other's mention, you need to use split() to separate individual items in the input:
userfoods = userinput.split()
But even after that your if condition isn't correct:
if foodgroups[0] or foodgroups[1] or foodgroups[2] or foodgroups[3] in userinput:
The thing to realize here is that or and in are operators that only work with the immediately adjacent 2 values. We can add parentheses to see how this works:
if (((foodgroups[0] or foodgroups[1]) or foodgroups[2]) or (foodgroups[3] in userinput)):
This means that foodgroups[0] or foodgroups[1] evaluates to just the value of foodgroups[0], so foodgroups[1] is basically ignored. This isn't what you want. Instead, you need to check in for each item:
if foodgroups[0] in userinput or foodgroups[1] in userinput or foodgroups[2] in userinput or foodgroups[3] in userinput:
But as you can see this gets very lengthy. So using a loop or list comprehension or generator expression can reduce the amount of code you need to write as others have already shown.
I have a python program that I am trying to create where the user can input a letter and the program filters out all the words that do not begin with this letter. Unfortunately me and my beginner brain cannot figure out how to write this in code, so any help?
The code I have already:
#Open list of words file and add to "content" variable
content = open('Word List').read().splitlines()
#Take the first character of every word and make a new variable to add that to.
firstchar = [x[0] for x in content]
#Ask the user which letter they'd like to use
print("Which letter would you like to use?")
u_selected = input("> ")
Not very much as you can see, but I'm proud of it. I figure I need something that uses firstchar[i] and u_selected to match the two letters together.
As you've done, you can use [0] to access the first character of a string. The below will add each word to a new list for you if it matches the condition specified.
chosen_words = [word for word in content if word.lower()[0] == u_selected.lower()]
The .lower() is to just to convert everything to lower case, to make sure case is ignored
Strings have there own methods to make things easier with strings.
dir(str)
You can test the beginning of a string with .startswith(). For example,
words = open('Word List').read().splitlines()
new_words = [word for word in words if word.startswith('A')]
To filter that you need to do:
#Open list of words file and add to "content" variable
content = open('Word List').read().splitlines()
#Ask the user which letter they'd like to use
print("Which letter would you like to use?")
u_selected = input("> ")
filtered_words = [word for word in content if word.startswith(u_selected)
I need to write a function that returns the first letters (and make it uppercase) of any text like:
shortened = shorten("Don't repeat yourself")
print(shortened)
Expected output:
DRY
and:
shortened = shorten("All terrain armoured transport")
print(shortened)
Expected output:
ATAT
Use list comprehension and join
shortened = "".join([x[0] for x in text.title().split(' ') if x])
Using regex you can match all characters except the first letter of each word, replace them with an empty string to remove them, then capitalize the resulting string:
import re
def shorten(sentence):
return re.sub(r"\B[\S]+\s*","",sentence).upper()
print(shorten("Don't repeat yourself"))
Output:
DRY
text = 'this is a test'
output = ''.join(char[0] for char in text.title().split(' '))
print(output)
TIAT
Let me explain how this works.
My first step is to capitalize the first letter of each work
text.title()
Now I want to be able to separate each word by the space in between, this will become a list
text.title()split(' ')
With that I'd end up with 'This','Is','A','Test' so now I obviously only want the first character of each word in the list
for word in text.title()split(' '):
print(word[0]) # T I A T
Now I can lump all that into something called list comprehension
output = [char[0] for char in text.title().split(' ')]
# ['T','I','A','T']
I can use ''.join() to combine them together, I don't need the [] brackets anymore because it doesn't need to be a list
output = ''.join(char[0] for char in text.title().split(' ')
I am trying to write a function that checks my input to see whether I have entered the character '?'.
This is what I got so far:
def check_word():
word = []
check = 0
user_input = input('Please enter a word that does not contain ?: ')
for token in user_input.split():
if token == '?':
print('Error')
check_word()
My input: hello?
It is supposed to show 'Error'. But it doesn't show anything. Could you please tell me what wrong it is in my code.
I would use the in operator to do this
def check_word(s):
if '?' in s:
print('Error')
For example
>>> check_word('foobar')
>>> check_word('foo?')
Error
The problem is how you split the string of the user_input.
user_input.split():
The example doesn't contain whitespaces so the condition isn't met. If you want for example to check a sentence with spaces, you should split it like this: user_input.split(' ') to split it on the spaces.
But for this example you have two choices:
1) You can just iterate over the input itself because you want to check every char in the string for whether it's a ?.
That is, change user_input.split(): into simply user_input without splitting. This option is good if you might ever want to add some sort of action for each char.
2) It's very easy just to use in, like this:
if '?' in s:
print('There is a question mark in the string')
This is a very simple solution that you can expand and check for other chars in the string as well.
It's because user_input.split() splits the user_input by whitespace. Since hello? does not contain any whitespaces, token is equal to your input and the loop is executed once.
You should iterate over user_input instead, or simply check if '?' in user_input.
Hello i am trying to make my program check for certain words in the user input. For example: The user types "add the numbers 6+6" what the programs does is it has a dictionary and checks the words in the dictionary and compares them to the words in the user input this example is "add". If the word add is in the user input then it checks for numbers and also math symbols this example is "6+6" then it outputs the answer?
I have tried:
if test == "add":
do something
but this will not work unless the word "add" is all by itself. any help is very much appreciated.
It will work only in the cases like add 6+6 or 6+6 add or add <some_text> 6+6 etc.
string = input()
if 'add' in string:
string = string.split('+')
no1 = int(string[0].split()[-1])
no2 = int(string[1].split()[0])
print(no1 + no2)
You can loop through the input words and check them in your dictionary like
for word in input:
if word in dic:
pass
fail
You can use the string.split() to split up the text into each word.
Then you can test each word individually for key words.
Details: http://docs.python.org/2/library/string.html
Look up the split method.
I'm pretty sure the split method by default returns a list of words split up by white space characters. So for example:
test_list = input.split()
test_list[1] should be 'add'
Best way to find out is to test it yourself, but I think it is something along those lines.
Cheers