I am trying to write a program to test if a word appears in a string and to print a different message depending on the number of upper case letters in the match.
For instance, searching for robot
in a string such as I saw a robot in the street...
would print There is a small robot.
, in I saw a rOBOt in the alleyway!
it would print There is a medium size robot.
, and if the string contains ROBOT
it would print There is a big robot.
.
This is what I have tried:
a = input("Line: ")
b = a.split()
if "robot" in b:
c = list("robot")
if c[0].isupper() or c[1].isupper() or c[2].isupper() or c[3].isupper() or c[4].isupper():
print("Small robot...")
else:
print("No robots here.")
I know it's kind of lengthy but it's how much I can do right now. How can I get it to find the word robot
in the string, regardless of position and to print the correct output?
You can check if a character is upper case via isupper()
:
s = "rOBOt"
percent_upper = sum(char.isupper() for char in s) / len(s)
print(percent_upper) # 0.6
Then just use that percent value in your if statements:
if percent_upper == 0:
print("small")
elif percent_upper == 1.0:
print("large")
else:
print("medium")
-- edit --
Here is a more complete solution that finds robot in the sentence:
import re
def get_robot_size(s):
percent_upper = sum(char.isupper() for char in s) / len(s)
return percent_upper
s = "I saw a ROBOt in the street"
robot_search = re.search(r'\brobot\b', s, flags=re.IGNORECASE)
if not robot_search: # no robot found
print("No robot found")
else:
robot_str = robot_search.group()
robot_size = get_robot_size(robot_str) # Get the percentage of capital letters
if robot_size == 0:
print("small")
elif robot_size == 1.0:
print("large")
else:
print("medium")
You could use regular expressions to first find if the word is present in a case insensitive way, and then count how many letters are upper case.
For instance:
import re
sentence = "I can see a mixed-case rObOT here"
# Search for the word 'robot' anywhere and regardless of case
matches = re.match(r"(?i).*\b(robot)\b.*", sentence)
if matches:
matching_word = matches.group(1)
# Iterate each letter in the match to count upper case ones
uppercase_count = 0
for l in matching_word:
if l.isupper():
uppercase_count += 1
# Print something different based on the number of upper case letters found
if uppercase_count < 2:
print("small robot")
elif uppercase_count < 4:
print("medium robot")
else:
print("big robot")
else:
print("no robot")
This is very specific to your example but can easily be generalised to any word.
I'd take a simple approach. First check if the lowercased keyword exists in the sentence. If not: check if the uppercased keyword exists. If not: check if the lowercased keyword exists in the lowercased words.
keyword = 'robot'
sentence = input("Line: ")
words = sentence.split()
if keyword.lower() in words:
print("There is a small robot.")
elif keyword.upper() in words:
print('There is a big robot.')
elif keyword.lower() in (word.lower() for word in words):
print('There is a medium size robot.')
else:
print('There is no robot.')
With minor modifications you could even check for different cases (eg "There is a robot and a second rOboT").
keyword = 'robot'
sentence = input("Line: ")
words = sentence.split()
keyword_found = False
if keyword.lower() in words:
keyword_found = True
print("There is a small robot.")
if keyword.upper() in words:
keyword_found = True
print('There is a big robot.')
if keyword.lower() in (word.lower() for word in words if word not in (keyword.lower(), keyword.upper())):
keyword_found = True
print('There is a medium size robot.')
if not keyword_found:
print('There is no robot.')
An explanation for the following line:
if keyword.lower() in (word.lower() for word in words if word not in (keyword.lower(), keyword.upper())):
In the condition we have to throw out an existing all lowercase or all uppercase keyword. That was not needed in the simple version of the code because that part would never have been reached due to the elif
.
Here is another approach that looks for the entire word and not the individual character types.
Since you have 3 sizes of robots, you could use a Dictionary to store the excepted string variables (robot, rOBOt, ROBOT) and their associated sentence output.
def get_user_input():
user_input = input('Type your sentence: ')
return user_input
def determine_robot_size(data):
robot_sizes = {'small': ('robot', 'There is a small robot.'),
'medium': ('rOBOt', 'There is a medium robot'),
'large': ('ROBOT', 'There is a big robot.'), }
for key, value in robot_sizes.items():
robot_size = value[0]
sentence = value[1]
if robot_size in data:
return sentence
sentence = get_user_input()
type_of_robot = determine_robot_size(sentence)
print (type_of_robot)
Here another way to accomplish your task using list comprehension.
I noted that you mentioned that you wanted to flag words like robotfest, so I added a length check to the list comprehension.
# obtain user input
user_input = input('Type your sentence: ')
# nested list containing robot types based on given string and
# the desired output associated with robot type
robot_sizes = [['robot', 'There is a small robot.'], ['rOBOt', 'There is a medium robot.'], ['ROBOT', 'There is a big robot.']]
# list comprehension
# robot_sizes[0] = the strings robot, rOBOt and ROBOT
robot = [robot for robot in robot_sizes[0] if robot for word in user_input.split() if len(word) == 5]
# Did the term robot exist in the input
if robot:
# print the output associated with the robot type
print (robot[1])
else:
print ('There were no robot sightings')
This works for me:
import re
a = input("Line: ")
b = a.split()
c = False
for i in range(len(b)):
if 'robot' == b[i]:
print('Small Robot')
c = True
break
elif 'ROBOT' == b[i]:
print('Big Robot')
c = True
break
elif 'robot' == b[i].lower():
if re.search('[a-z]', b[i]) and re.search('[A-Z]', b[i]):
print('Medium Robot')
c = True
break
if not c:
print('No Robot')
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.