- 如果字符串中含有 %20,则需要将其替换为 OR,例如 abc %20 def。期望输出 -->
'*abc* OR *def*'
- 如果字符串中含有逗号,则需要将其替换为 OR,例如 abc,def。期望输出 -->
'*abc* OR *def*'
- 字符串 = 'abc def':需要更新每个字符串的开头和结尾,并用 * 替换空格并使用 OR。期望输出 -->
'*abc* OR *def*'
- 字符串 = 'abc or def'、'abc+def'、'abc + def'、'abc OR def':如果字符串中存在 OR 或 +,则需要进行更新。期望输出 -->
'*abc* OR *def*'
- 字符串 = 'abc&def'、'abc & def'、'abc and def'、'abc AND def':如果字符串中存在 AND 或 &,则需要进行更新。期望输出 -->
'*abc* AND *def*'
- 字符串 = 'abc':期望输出 -->
'*abc*'
- 字符串 = 'abc def ghi':期望输出 -->
'*abc* OR *def* OR *ghi*'
- 所有标点符号都必须被替换
以下是代码:
import re
def format_search_value(search_value_1):
punctuations = '''!()[]{};:"\,<>./?@#%^*~'''
search_value_1 = search_value_1.replace('+', ' ')
#if %20 there in the string it has to replace with OR, abc %20 def
search_value_1 = re.sub('^(%20)+$', '%20', search_value_1)
search_value = ""
for char in search_value_1:
if char not in punctuations:
search_value = search_value + char
search_expression = ','.join([f'*{word.strip()}*' for word in search_value.split(',')])
search_expression = re.sub(' +', ' ', search_expression.replace('%20', ' '))
search_expression = ','.join([f'*{word}*' for word in search_expression.split(' ')])
search_parameter = search_expression.replace('%20', ' OR ').replace(',', ' OR ') \
.replace('and', 'AND').replace('+', 'OR').replace('or', 'OR').strip()
search_parameter = search_parameter.replace('**', '*')
return search_parameter
format_search_value('abc or def')
我只在输入“abc def”且查询条件为'*abc* OR *def*'
时才得到正确的输出。