簡體   English   中英

從字符串中刪除特定單詞的最有效方法

[英]Most efficient way to remove specific words from a string

可以說我有以下字符串,

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中有更有效的方法嗎? 我所顯示的只是我正在處理的字符串的一個示例。 我還需要刪除許多其他帶有不同單詞的字符串,例如cupscuptablespoonsteaspoon 我正在使用相同的方法從字符串中消除單詞,那么是否有更好的方法呢?

您可能要使用正則表達式。

import re

words = r'oz|lbs?|cups?|tablespoons?|tea‌​spoons?|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'

正則表達式對於通過字符串進行解析非常有用。 有了它們,您就可以搜索所需字符串始終匹配的時間,並從中找出一個新字符串。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM