0

我需要在这样的字符串中的子字符串(包含 OR 布尔运算符)周围添加括号:

message = "a and b amount OR c and d amount OR x and y amount"

我需要达到这个:

message = "(a and b amount) OR (c and d amount) OR (x and y amount)"

我试过这段代码:

import shlex
message = "a and b amount OR c and d amount OR x and y amount"
target_list = []

#PROCESS THE MESSAGE.
target_list.append(message[0:message.index("OR")])
args = shlex.split(message)
attribute = ['OR', 'and']
var_type = ['str', 'desc']

for attr, var in zip(attribute, var_type):
    for word in args:
        if word == attr and var == 'str': target_list.append(word+' "')
        else: target_list.append(word)
print(target_list)

但这似乎不起作用,代码只是返回原始消息的多个副本,并且没有在句尾添加括号。我该怎么办?

4

3 回答 3

0

一些字符串操作函数应该可以在不涉及外部库的情况下解决问题

" OR ".join(map(lambda x: "({})".format(x), message.split(" OR ")))

或者,如果您想要更易读的版本

sentences = message.split(" OR ")
# apply parenthesis to every sentence
sentences_with_parenthesis = list(map(lambda x: "({})".format(x), sentences))
result = " OR ".join(sentences_with_parenthesis)
于 2018-10-20T01:22:27.540 回答
0

如果您的字符串始终是由 OR 分隔的术语列表,则可以拆分并加入:

>>> " OR ".join("({})".format(s.strip()) for s in message.split("OR"))
'(a and b amount) OR (c and d amount) OR (x and y amount)'
于 2018-10-20T01:23:07.433 回答
0

您可能只想将所有子句分解成一个列表,然后用括号将它们连接起来。像这样的东西,尽管它添加了括号,即使没有 OR 子句:

original = "a and b OR c and d OR e and f"
clauses = original.split(" OR ")
# ['a and b', 'c and d', 'e and f']
fixed = "(" + ") OR (".join(clauses) + ")"
# '(a and b) OR (c and d) OR (e and f)'
于 2018-10-20T01:26:10.543 回答