如何提取一个子串并生成子串

2024-06-06 17:41:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在识别一个子串后提取并构造一些字符串,该子字符串与方形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

Tags: to字符串textreifmatchmetric方形
2条回答

我只是在扩展布伦巴恩接受的答案。我喜欢午餐时解决一个好问题。以下是我对你的问题的全面理解:

给定字符串2 cups [9 oz] [10 g] flour

import re

text = '2 cups [9 oz] [10 g] flour' 

units = {'oz': 'uk imperical', 
         'cups': 'us', 
         'g': 'metric'}

# strip out brackets & trim white space
text = text.replace('[', '').replace(']', '').strip()

# replace numbers like 9 to "9
text = re.sub(r'(\d+)', r'"\1', text)

# expand units like `cups` to `cups" -> us`
for unit in units:
    text = text.replace(unit, unit + '" -> ' + units[unit] + "~")

# matches the last word in the string
text = re.sub(r'(\w+$)', r'"\1" -> ingredient name', text)

print "raw text: \n" + text + "\n"
print "Array:"
print text.split('~ ')

将返回字符串数组:

^{pr2}$

您需要使用search而不是match。在

m = p_oz.search(text)

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

相关问题 更多 >