简体   繁体   English

如何在字符串中搜索单词并根据匹配的大小写不同的打印?

[英]How to search for word in a string and print differently based on the case of the match?

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.例如,在字符串中搜索robot ,例如I saw a robot in the street...会打印出There is a small robot. , in I saw a rOBOt in the alleyway! ,在I saw a rOBOt in the alleyway! it would print There is a medium size robot.它会打印There is a medium size robot. , and if the string contains ROBOT it would print There is a big robot. , 如果字符串包含ROBOT它将打印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?我怎样才能让它在字符串中找到robot这个词,不管位置如何并打印正确的输出?

You can check if a character is upper case via isupper() : 您可以通过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语句中使用该百分比值:

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 . 在简单的代码版本中不需要这样做,因为由于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. 由于您有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)

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. 我注意到您提到您想标记诸如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')

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')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM