簡體   English   中英

Python正則表達式替換\\ u2022

[英]Python regex replacing \u2022

這是我的字符串:

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.'

我正在嘗試僅用空格替換\•

x=re.sub(r'\u2022', ' ', raw_list)

但這不起作用。 我究竟做錯了什么?

您正在使用帶有r的原始字符串。 這告訴Python從字面上解釋字符串,而不是實際使用轉義字符(例如\\ n)。

>>> r'\u2022'
'\\u2022'

您可以看到它實際上是一個雙反斜杠。 相反,您想使用>>> u'\•' ,然后它將起作用。

請注意,由於您要進行簡單的替換,因此只能使用str.replace方法:

x = raw_list.replace(u'\u2022', ' ')

您只需要使用正則表達式替換即可進行復雜的模式匹配。

除非您使用Unicode字符串文字,否則\\uhhhh轉義序列沒有任何意義。 不用於Python,也不用於re模塊。 添加u前綴:

re.sub(ur'\u2022', ' ', raw_list)

注意那里的ur 那是原始的unicode字符串文字; 這仍然會解釋\\uhhhh Unicode轉義序列(但在其他方面與標准原始字符串文字模式相同)。 re模塊本身不支持此類轉義序列(但它支持大多數其他Python字符串轉義序列)。

不必在這里使用正則表達式,一個簡單的unicode.replace()就足夠了:

raw_list.replace(u'\u2022', u' ')

或者您可以使用unicode.translate()

raw_list.translate({0x2022: u' '})

這是我的方法,更改正則表達式模式,您可以嘗試

re.sub(r'[^\x00-\x7F]+','',raw_list)

出[1]:u'軟件工程師,對新的創新產品充滿熱情。 從大型和快速成長的初創公司工作中積累的經驗。 特殊語言和框架:JavaScript(Nodejs,React),Android,Ruby on Rails 4,iOS(Swift)數據庫:Mongodb,Postgresql,MySQL,Redis測試框架:Mocha,Rspec xxxx其他:Sphinx,MemCached,Chef。

關鍵是將unicode u添加到要查找的unicode字符之前-在本例中為\• ,它是項目符號的unicode字符。 如果您的文本包含unicode字符,則您的文本實際上是unicode文本,而不是字符串(您可以通過打印文本並在開頭查找u來進行確認)。 請參見下面的示例,在該示例中,我同時在字符串和unicode文本上使用正則表達式(RegEx)搜索Unicode項目符號字符:

導入正則表達式包:
 import re 
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 
串:
 my_string = """\• Here\\'sa string of data. \\n<br/>\•There are new line characters \\n, HTML line break tags <br/>, and bullets \  together in a sequence.\\n<br/>\• Our goal is to use RegEx to identify the sequences.""" type(my_string) #string 
我們成功找到了要查找的第一段文本,但該段文本尚未包含unicode字符:
re.findall('\n<br/>\\\\u', my_unicode)

re.findall('\n<br/>\\\\u', my_string)
加上unicode字符,找不到任何子字符串:
 re.findall('\\n<br/>\•', my_unicode) re.findall('\\n<br/>\•', my_string) 
添加四個反斜杠適用於該字符串,但不適用於unicode文本:
 re.findall('\\n<br/>\\\\\\\\u\u0026#39;, my_unicode) re.findall('\\n<br/>\\\\\\\\u\u0026#39;, my_string) 
解決方案:在unicode字符前面包括unicode u
 re.findall('\\n<br/>' u'\•', my_unicode) 

暫無
暫無

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

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