Python正则表达式替换\u2022
这是我的字符串:Python正则表达式替换\u2022,python,regex,Python,Regex,这是我的字符串: raw_list = u'Software Engineer with a huge passion for new and innovative products. Experienced gained from working in both big and fast-growing start-ups. Specialties \u2022 Languages and Frameworks: JavaScript (Nodejs, React), Android, Ru
raw_list = u'Software Engineer with a huge passion for new and innovative products. Experienced gained from working in both big and fast-growing start-ups. Specialties \u2022 Languages and Frameworks: JavaScript (Nodejs, React), Android, Ruby on Rails 4, iOS (Swift) \u2022 Databases: Mongodb, Postgresql, MySQL, Redis \u2022 Testing Frameworks: Mocha, Rspec xxxx Others: Sphinx, MemCached, Chef.'
我试图用一个空格来替换\u2022
x=re.sub(r'\u2022', ' ', raw_list)
但它不起作用。我做错了什么?除非使用Unicode字符串文字,否则转义序列没有任何意义。不适用于Python,也不适用于re
模块。添加u
前缀:
re.sub(ur'\u2022', ' ', raw_list)
注意那里的
ur
;这是一个原始的unicode字符串文字;这仍然解释unicode转义序列(但在其他方面与标准原始字符串文字模式相同)。re
模块本身不支持此类转义序列(但它支持大多数其他Python字符串转义序列)
这里不需要使用正则表达式,简单的表达式就足够了:
raw_list.replace(u'\u2022', u' ')
或者您可以使用:
您使用的是原始字符串,带有
r
。这告诉Python按字面解释字符串,而不是实际使用转义字符(例如\n)
你可以看到它实际上是一个双反斜杠。相反,您希望使用>>>u'\u2022'
,然后它就可以工作了
请注意,由于您正在进行简单的替换,因此只需使用str.replace
方法即可:
x = raw_list.replace(u'\u2022', ' ')
对于复杂的模式匹配,您只需要替换正则表达式。这是我的方法,更改正则表达式模式,您可以尝试
re.sub(r'[^\x00-\x7F]+','',raw_list)
Out[1]:你是一名软件工程师,对新技术和新技术有着巨大的热情
创新产品。在大、中型企业工作经验丰富
快速成长的初创企业。语言和框架:
JavaScript(Nodejs、React)、Android、RubyonRails4、iOS(Swift)
数据库:Mongodb、Postgresql、MySQL、Redis测试框架:
摩卡咖啡,Rspec xxxx其他:斯芬克斯,MemCached,厨师
关键是在您试图查找的unicode字符前面添加unicode
u
——在本例中是\u2022
,它是项目符号的unicode字符。如果文本包含unicode字符,则文本实际上是unicode文本,而不是字符串(您可以通过打印文本并在开头查找u来确认)。请参见下面的示例,其中我使用正则表达式(RegEx)在字符串和unicode文本上搜索unicode项目符号字符:
导入正则表达式包:
unicode文本:
您不需要使用
re
模块来执行此操作。只需使用unicode字符串的.replace()
方法即可。请注意,re
模块会解释Python支持的大多数字符串转义序列<代码>\uhhh恰好是一个不受支持的代码。您仍然可以使用原始字符串文字,只需在前面添加u
就可以解释Unicode转义序列。“这仍然解释\uhhh
Unicode转义序列”-哇,我没想到会是这样。我不知道他们为什么会那样做。看起来他们是为了避免ur
应该是真正原始的还是像Python 2那样只是有点原始的问题。@user2357112:在Python 3中不需要ur'…'
,因为a)r'…'
已经是unicode字符串(因为在Python 3中字符串总是unicode字符串)b)在Python3中,re
模块确实支持\uhhh
序列。
x = raw_list.replace(u'\u2022', ' ')
re.sub(r'[^\x00-\x7F]+','',raw_list)
import re
my_unicode = u"""\u2022 Here\'s a string of data.\n<br/>\u2022 There are new
line characters \n, HTML line break tags <br/>, and bullets \u2002 together in
a sequence.\n<br/>\u2022 Our goal is to use RegEx to identify the sequences."""
type(my_unicode) #unicode
my_string = """\u2022 Here\'s a string of data. \n<br/>\u2022There are new
line characters \n, HTML line break tags <br/>, and bullets \u2002 together in
a sequence.\n<br/>\u2022 Our goal is to use RegEx to identify the sequences."""
type(my_string) #string
re.findall('\n<br/>', my_unicode)
re.findall('\n<br/>', my_string)
re.findall('\n<br/>\u2022', my_unicode)
re.findall('\n<br/>\u2022', my_string)
re.findall('\n<br/>\\\\u', my_unicode)
re.findall('\n<br/>\\\\u', my_string)
re.findall('\n<br/>' u'\u2022', my_unicode)