假设我有以下字符串,
ing = "2 cup butter, softened"
我只希望字符串中有butter
(到目前为止我已完成以下操作),
ing.replace('2','').replace('cup','').replace(', ','').replace('softened','')
ing.strip()
修改
Traceback (most recent call last):
File "parsley.py", line 107, in <module>
leaf.write_ingredients_to_csv()
File "parsley.py", line 91, in write_ingredients_to_csv
out = re.sub(words, '', matched)
File "C:\Users\Nikhil\Anaconda3\lib\re.py", line 191, in sub
return _compile(pattern, flags).sub(repl, string, count)
File "C:\Users\Nikhil\Anaconda3\lib\re.py", line 301, in _compile
p = sre_compile.compile(pattern, flags)
File "C:\Users\Nikhil\Anaconda3\lib\sre_compile.py", line 562, in compile
p = sre_parse.parse(p, flags)
File "C:\Users\Nikhil\Anaconda3\lib\sre_parse.py", line 855, in parse
p = _parse_sub(source, pattern, flags & SRE_FLAG_VERBOSE, 0)
File "C:\Users\Nikhil\Anaconda3\lib\sre_parse.py", line 416, in _parse_sub
not nested and not items))
File "C:\Users\Nikhil\Anaconda3\lib\sre_parse.py", line 752, in _parse
len(char) + 1)
sre_constants.error: unknown extension ?| at position 23
在Python 3中有更有效的方法吗?我所展示的只是我正在处理的字符串的一个示例。我还需要删除更多包含不同字词的字符串,例如cups
,cup
,tablespoons
和teaspoon
。我使用相同的方法来消除字符串中的单词,那么有更好的方法吗?
答案 0 :(得分:2)
您可能想要使用正则表达式。
import re
words = r'oz|lbs?|cups?|tablespoons?|teaspoons?|softened'
words_rm = r'slices?|shredded|sheets?|cans?|\d ?g\b'
other = r'[\d,;#\(\)\[\]\.]'
ing = "2 cup butter, softened"
out = re.sub(words, '', ing)
out = re.sub(words_rm, '', out)
out = re.sub(other, '', out)
out.strip()
# returns:
'butter'
答案 1 :(得分:0)
Regular Expressions对于解析字符串非常有用。使用它们,您可以搜索所需的字符串匹配的所有时间,并从中创建一个新的字符串。