gpt4 book ai didi

python - 如何提取由 square braquet 分隔的子串并生成子串

转载 作者:太空宇宙 更新时间:2023-11-04 09:14:32 24 4
gpt4 key购买 nike

我想在识别出与正方形 braquets 中包含的模式匹配的子字符串后提取并构造一些字符串:

e.g: if my text is '2 cups [9 oz] [10 g] flour '

i want to generate 4 strings out of this input:

  1. "2 cups" -> us
  2. "9 oz" -> uk imperial
  3. "10 g" -> metric
  4. "flour" -> ingredient name

作为开始,我已经开始识别任何包含 oz 关键字的方形 braquet 并编写了以下代码,但匹配没有发生。有什么想法和最佳实践来实现这一目标吗?

    p_oz = re.compile(r'\[(.+) oz\]', re.IGNORECASE) # to match uk metric
text = '2 cups [9 oz] flour'

m = p_oz.match(text)

if m:
found = m.group(1)
print found

最佳答案

您需要使用search 而不是match

m = p_oz.search(text)

re.match 尝试将整个输入字符串与正则表达式进行匹配。那不是你想要的。您想要找到与您的正则表达式匹配的子字符串,这就是 re.search 的用途。

关于python - 如何提取由 square braquet 分隔的子串并生成子串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11212014/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com