[英]How to search for word in a string and print differently based on the case of the match?
我正在尝试编写一个程序来测试一个单词是否出现在字符串中,并根据匹配中大写字母的数量打印不同的消息。
例如,在字符串中搜索robot
,例如I saw a robot in the street...
会打印出There is a small robot.
,在I saw a rOBOt in the alleyway!
它会打印There is a medium size robot.
, 如果字符串包含ROBOT
它将打印There is a big robot.
.
这是我尝试过的:
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.")
我知道这有点冗长,但这是我现在能做的事情。 我怎样才能让它在字符串中找到robot
这个词,不管位置如何并打印正确的输出?
您可以通过isupper()
检查字符是否为大写:
s = "rOBOt"
percent_upper = sum(char.isupper() for char in s) / len(s)
print(percent_upper) # 0.6
然后在if语句中使用该百分比值:
if percent_upper == 0:
print("small")
elif percent_upper == 1.0:
print("large")
else:
print("medium")
-编辑-
这是在句子中找到机器人的更完整的解决方案:
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")
您可以使用正则表达式首先确定单词是否以不区分大小写的方式出现,然后计算多少个字母为大写。
例如:
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")
这是非常具体的示例,但可以很容易地推广到任何单词。
我会采取一种简单的方法。 首先检查小写关键字是否存在于句子中。 如果不是,请检查是否存在大写关键字。 如果不是,请检查小写单词中是否存在小写关键字。
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.')
进行较小的修改,您甚至可以检查不同的情况(例如“有一个机器人和另一个机器人”)。
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.')
以下行的说明:
if keyword.lower() in (word.lower() for word in words if word not in (keyword.lower(), keyword.upper())):
在这种情况下,我们必须丢弃现有的全部小写或全部大写的关键字。 在简单的代码版本中不需要这样做,因为由于elif
,该部分永远都无法达到。
这是寻找整个单词而不是单个字符类型的另一种方法。
由于您有3种大小的机械手,您可以使用字典来存储例外的字符串变量(机械手,rOBOt,机械手)及其关联的句子输出。
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)
这是使用列表理解来完成任务的另一种方法。
我注意到您提到您想标记诸如robotfest之类的词,因此我在列表理解中添加了长度检查。
# 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')
这对我有用:
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')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.