我有一个带Unicode的字符串。我想用Unicode作为分隔符将字符串分为左子字符串和右子字符串。
例如,给定的字符串为:
str = 'Oh wow. Magnificent! Ariadna Garcia! <U+2764> <U+2764> wonderful'
我希望输出为:
leftstr = 'Oh wow. Magnificent! Ariadna Garcia!'
uni_code = '<U+2764> <U+2764>'
rightstr = 'wonderful'
我想到了使用正则表达式来标识Unicode,然后使用find()查找Unicode的索引。然后使用带有索引的字符串切片和剪切方法,即leftstr =起始索引比unicode的索引小一。然后,rightstr =(Unicode的起始索引+ Unicode的长度)直到字符串的结尾。问题是我识别Unicode的正则表达式无法正常工作。我觉得我的方法很复杂。是否有任何优雅的方法来获取所需的子字符串作为输出。
以下代码,到目前为止,我已经尝试过:
import re str1 = 'Oh wow. Magnificent! Ariadna Garcia! <U+2764> wonderful'
pattern = r'<U\+.*?>'
indx = str1.find(pattern)
print(indx)
正则表达式无法正常工作。
不幸的是,表情符号很多,其中许多是多个序列,因此通用解决方案很复杂。这是Unicode的完整列表:
https://unicode.org/emoji/charts-13.0/emoji-list.html
直接的解决方案是:
import re
s = 'Oh wow. Magnificent! Ariadna Garcia! ❤ ❤ wonderful'
left,emoji,right = re.split(r'(\u2764 \u2764)',s)
print(left,emoji,right,sep='\n')
Oh wow. Magnificent! Ariadna Garcia!
❤ ❤
wonderful
您可以解析这些Unicode data files以创建更复杂的正则表达式。例如,这解析了一系列图释:
import re
s = 'One😀Two😁Three😂Four😃Five'
result = re.split(r'([\U0001F600-\U0001F64F])',s)
print(result)
['One', '😀', 'Two', '😁', 'Three', '😂', 'Four', '😃', 'Five']