在句子的两个符号之间输入文本



任务是获取句子中两个符号之间的文本。用户在下一行中的一行中输入句子,然后输入符号(在本例中为[和](。

示例:

In this sentence [need to get] only [few words].

输出需要看起来像:

need to get few words

有人知道怎么做吗?

我有一些想法,比如拆分输入,所以我们将访问列表中的每个元素,如果第一个符号是[并以]结束,我们将该单词保存到其他列表中,但如果该单词没有以]结束,就会出现问题

p.S.用户永远不会像[word [another] word]那样输入空字符串或在符号内有符号

您可以使用正则表达式:

import re
text = 'In this sentence [need to get] only [few words] and not [unbalanced'

' '.join(re.findall(r'[(.*?)]', text))

输出:'need to get few words'

或使用查找将'(?<=[).*?(?=])'作为正则表达式

  1. 您可以使用这样的正则表达式:
import re
your_string = "In this sentence [need to get] only [few words]"
matches = re.findall(r'[([^[]]*)]', your_string)
print(' '.join(matches))

Regex演示

  1. 不带正则表达式的解决方案:
your_string = "In this sentence [need to get] only [few words]"
result_parts = []
current_square_brackets_part = ''
need_to_add_letter_to_current_square_brackets_part = False
for letter in your_string:
if letter == '[':
need_to_add_letter_to_current_square_brackets_part = True
elif letter == ']':
need_to_add_letter_to_current_square_brackets_part = False
result_parts.append(current_square_brackets_part)
current_square_brackets_part = ''
elif need_to_add_letter_to_current_square_brackets_part:
current_square_brackets_part += letter
print(' '.join(result_parts))

这里有一个使用解析的更经典的解决方案。

它逐字符读取字符串,并且只有在设置了标志时才保留它。当遇到[并且未设置在]时设置该标志

text = 'In this sentence [need to get] only [few words] and not [unbalanced'
add = False
l = []
m = []
for c in text:
if c == '[':
add = True
elif c == ']':
if add and m:
l.append(''.join(m))
add = False
m = []
elif add:
m.append(c)
out = ' '.join(l)
print(out)

输出:need to get few words

最新更新