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
Related
I just want to make an input text:
text = input('Your text: ')
And after the user types the text, I want the programme to take only capital letters from it and print them.
What does the easiest way mean? - Well, try to not use
functions, lists and stuff like that. Try to make the programme as
easy as possible. Thanks beforehand.
for char in text:
if char.isupper():
print(char)
A couple of inline ways to do it:
List comprehensions:
uppercase_chars = [char for char in text if char.isupper()]
Filter functions:
uppercase_chars = filter(str.isupper,text)
Although these answers both return lists, we can easily collapse them to strings using str.join like so:
''.join(uppercase_chars)
These are not as simple as BVB44's answer, but they're much more likely to be seen in real-world code.
Use a for loop to check if each character is uppercase, and add it to a new variable if it is. How this works is:
For every character in the variable my_string, Python checks if the character is uppercase. If it is, it adds it to the variable output. This keeps everything on one line.
my_string = input("Type some stuff ")
output = ''
for char in my_string:
if char.isupper():
output = output + char
print(output)
My question is pretty simple, but I haven't been able to find a proper solution.
Given below is my program:
given_list = ["Terms","I","want","to","remove","from","input_string"]
input_string = input("Enter String:")
if any(x in input_string for x in given_list):
#Find the detected word
#Not in bool format
a = input_string.replace(detected_word,"")
print("Some Task",a)
Here, given_list contains the terms I want to exclude from the input_string.
Now, the problem I am facing is that the any() produces a bool result and I need the word detected by the any() and replace it with a blank, so as to perform some task.
Edit: any() function is not required at all, look for useful solutions below.
Iterate over given_list and replace them:
for i in given_list:
input_string = input_string.replace(i, "")
print("Some Task", input_string)
No need to detect at all:
for w in given_list:
input_string = input_string.replace(w, "")
str.replace will not do anything if the word is not there and the substring test needed for the detection has to scan the string anyway.
The problem with finding each word and replacing it is that python will have to iterate over the whole string, repeatedly. Another problem is you will find substrings where you don't want to. For example, "to" is in the exclude list, so you'd end up changing "tomato" to "ma"
It seems to me like you seem to want to replace whole words. Parsing is a whole new subject, but let's simplify. I'm just going to assume everything is lowercase with no punctuation, although that can be improved later. Let's use input_string.split() to iterate over whole words.
We want to replace some words with nothing, so let's just iterate over the input_string, and filter out the words we don't want, using the builtin function of the same name.
exclude_list = ["terms","i","want","to","remove","from","input_string"]
input_string = "one terms two i three want to remove"
keepers = filter(lambda w: w not in exclude_list, input_string.lower().split())
output_string = ' '.join(keepers)
print (output_string)
one two three
Note that we create an iterator that allows us to go through the whole input string just once. And instead of replacing words, we just basically skip the ones we don't want by having the iterator not return them.
Since filter requires a function for the boolean check on whether to include or exclude each word, we had to define one. I used "lambda" syntax to do that. You could just replace it with
def keep(word):
return word not in exclude_list
keepers = filter(keep, input_string.split())
To answer your question about any, use an assignment expression (Python 3.8+).
if any((word := x) in input_string for x in given_list):
# match captured in variable word
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 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.
For a game that asks input from the user, I am using an if check to determine what the user said. It's for a text based game here, so when a user inputs "examine table" I want examine to become a variable and table to become another variable so I can evaluate them separately in my script.
A variable named "move" is used for the input.
move = input("> ")
I want that variable to split into "action" and "object" variables by splitting the two words in half.
How would I go around doing this?
verb, _, params = move.partition(" ")
verb will be first word
_ will be the separator, whitespace in this case
params will be the rest after the verb
First you want to get the input:
varName = raw_input("Enter anything: ")
Then you want to split the input
splitted_results = varName.split()
print splitted_results
This will give you a list of strings split by empty space. You can loop through as so:
for sr in splitted_results:
print sr
Are you asking how to split a string into 2 different variables?
If so,
string = 'examine table'
splitString = string.split()
giving you the list
['examine','table']
Is it a string? If so, split up the string by whatever character you want to with
string.split("[character to split by here]")
Then, you will get an array. If you only wanted to split by the first character (let's say for example a period):
arr = string.split(".")
arr = [arr[0], ','.join(arr[1:])]