簡體   English   中英

如何在字符串中搜索單詞並根據匹配的大小寫不同的打印?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM