但它不起作用。
我如何解决我的问题?
def clean_text(text):
pattern = '([a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+)'
text = re.sub(pattern=pattern, repl='', string=text)
pattern = '(http|ftp|https)://(?:[-\w.]|(?:%[\da-fA-F]{2}))+'
text = re.sub(pattern=pattern, repl='', string=text)
pattern = '([ㄱ-ㅎㅏ-ㅣ]+)'
text = re.sub(pattern=pattern, repl='', string=text)
pattern = '<[^>]*>'
text = re.sub(pattern=pattern, repl='', string=text)
pattern = '[^\w\s]'
text = re.sub(pattern=pattern, repl='', string=text)
pattern = '\([^)]*\)' ## not working!!
text = re.sub(pattern=pattern, repl='', string=text)
return text
text = '(abc_def) 좋은글! (이것도 지워조) http://1234.com 감사합니다. aaa@goggle.comㅋㅋ<H1>thank you</H1>'
clean_text(text)
结果是abc_def 좋은글 Been도 지워조 감사합니다谢谢
我的目标是좋은글 감사합니다谢谢
最佳答案
您的 [^\w\s]
re.sub 删除了括号,因此最后一个正则表达式不匹配。您可以交换最后两个 re.sub 并使用
import re
def clean_text(text):
pattern = '([a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+)'
text = re.sub(pattern=pattern, repl='', string=text)
pattern = r'(?:http|ftp|https)://(?:[-\w.]|(?:%[\da-fA-F]{2}))+'
text = re.sub(pattern=pattern, repl='', string=text)
pattern = r'[ㄱ-ㅎㅏ-ㅣ]+'
text = re.sub(pattern=pattern, repl='', string=text)
pattern = r'<[^>]*>'
text = re.sub(pattern=pattern, repl='', string=text)
pattern = r'\s*\([^)]*\)'
text = re.sub(pattern=pattern, repl='', string=text)
pattern = r'[^\w\s]'
text = re.sub(pattern=pattern, repl='', string=text)
return text.strip()
text = '(abc_def) 좋은글! (이것도 지워조) http://1234.com 감사합니다. aaa@goggle.comㅋㅋ<H1>thank you</H1>'
print(clean_text(text))
请参阅online Python demo .
我建议使用原始字符串文字(注意 r''
前缀)并使用 text.strip()
去除不必要的空格。 r'\s*\([^)]*\)'
中的 \s*
将删除括号前的 0 个或多个空格。
关于python - 如何使用 python 中的正则表达式删除括号内的文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57145497/