3

我怎样才能删除“(”?
正确吗?:

import re, sys
my_source = {}
list_of_words  = {}
text_we_need   = {}
dict_of_words  = {}
max_characters = 0
with open("my_source2.txt") as f:
    my_source = f.read()
p = re.compile(r'<a(.*?)</a>')
my_source = p.sub('<a></a>', my_source, re.DOTALL)
my_source = re.sub('<a>','',my_source)
my_source = re.sub('(','',my_source)
my_source = re.sub(')','',my_source)

为什么这段代码不适用于'('??

4

3 回答 3

5

(并且)是正则表达式中的特殊字符,因为它们用于分组。您需要转义()使用\.

my_source = re.sub('\(','',my_source)
my_source = re.sub('\)','',my_source)
于 2013-09-15T14:42:59.863 回答
0

也将其发布在您的另一个线程上:

不要对这么简单的事情使用正则表达式。使用翻译:

Python 字符串文档

>>> str = "This is a (string) (example)..."
>>> str.translate(None, "()")
'This is a string example...'
>>>
于 2013-09-15T15:47:00.610 回答
0

我环顾四周,发现了几个类似的问题。

  1. Python剥离多个字符
  2. 正则表达式如何从字符串中删除符号 Python
  3. 如何在 Python 上使用正则表达式删除括号

似乎“双引号”应该起作用,而不是“单引号”。

于 2013-09-15T14:46:29.610 回答