【问题标题】:Get text between two signs in a sentence获取句子中两个符号之间的文本
【发布时间】:2022-01-24 01:36:07
【问题描述】:

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

例子:

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

输出需要如下所示:

need to get few words

有人知道怎么做吗?

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

附注用户永远不会输入空字符串或在[word [another] word] 之类的符号内添加符号。

【问题讨论】:

  • 请举例说明您的问题。这将有助于提供更清晰、更可靠的答案。
  • 如果你仔细阅读文本你会发现我做到了。
  • 你已经做到了,但是格式不正确,很难理解。
  • 已编辑,希望现在可以了。

标签: python string


【解决方案1】:
  1. 您可以像这样使用regular expressions
import re

your_string = "In this sentence [need to get] only [few words]"
matches = re.findall(r'\[([^\[\]]*)]', your_string)
print(' '.join(matches))

Regex demo

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

【讨论】:

  • 还没有学过。有没有其他方法?也许更容易和初学者?
  • 使用不带正则表达式的解决方案更新了答案。
【解决方案2】:

您可以使用正则表达式:

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'

'(?<=\[).*?(?=\])' 使用环视作为正则表达式

【讨论】:

  • 还没有学过。有没有其他方法?也许更容易和初学者?
  • @Kalaba 我提供了。 another solution 没有正则表达式
【解决方案3】:

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

它逐个字符地读取字符串,并仅在设置了标志时才保留它。遇到 [ 时设置标志,并在 ] 上取消设置

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

【讨论】:

    猜你喜欢
    • 2019-09-09
    • 2012-08-17
    • 2019-10-10
    • 2023-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-02
    相关资源
    最近更新 更多