Python 如何在正则表达式中包含重音词
我有一个utf-8文本,文本中有大写的单词:Python 如何在正则表达式中包含重音词,python,regex,capitalization,Python,Regex,Capitalization,我有一个utf-8文本,文本中有大写的单词: La cinta, que hoy se estrena en nuestro país, competirá contra Hors la Loi, de Argelia, Dogtooth, de Grecia, Incendies, de Canadá, Life above all , de Sudáfrica, y con la ganadora del Globo de Oro, In A Better World, de Dinamar
La cinta, que hoy se estrena en nuestro país, competirá contra Hors la
Loi, de Argelia, Dogtooth, de Grecia, Incendies, de Canadá, Life above
all , de Sudáfrica, y con la ganadora del Globo de Oro, In A Better
World, de Dinamarca.
所需的输出是将除第一个单词外的所有以大写字母开头的单词替换为占位符(即#NE
)。因此,所需的输出如下所示:
La cinta, que hoy se estrena en nuestro país, competirá contra #NE#
la #NE# , de #NE# , #NE# , de #NE# , #NE# , de #NE#, #NE# above
all , de #NE# , y con la ganadora del #NE# de #NE# , #NE# A #NE# #NE# , de #NE# .
我尝试使用regex,如下所示:
>>> import re
>>> def blind_CAPS_without_first_word(text):
... first_word, _, the_rest = text.partition(' ')
... blinded = re.sub('(?:[A-Z][\w]+\s*)', ' #NE# ', the_rest)
... return " ".join([first_word, blinded])
...
>>> text = "La cinta, que hoy se estrena en nuestro país, competirá contra Hors la Loi, de Argelia, Dogtooth, de Grecia, Incendies, de Canadá, Life above all , de Sudáfrica, y con la ganadora del Globo de Oro, In A Better World, de Dinamarca."
>>> blind_CAPS_without_first_word(text)
[out]:
在新的一年里,我们将在新的一年里,在竞争中获胜#
la#NE#,de#NE#,#NE#,de#NE#,#NE#,de#NE#,NE##
最重要的是,德涅菲卡,我是加纳多拉·德涅、涅、涅、涅
<>但正则表达式在使用<代码> \W时不考虑重音字符,如:代码> CANADA< <代码> >代码>code>Sudáfrica->#NE#áfrica
我该如何解决这个问题?如何在我的正则表达式中包含重音词?它需要是Canadá
->#NE#
Sudáfrica
->#NE#
我想,如果忽略像
A
这样的单字符单词仍然是A
,也没关系。除非有办法解决这个问题。因为\w+
或[\w]+
与重音字符不匹配。因此,它无法匹配这些词
您可以使用\S+
而不是\w+
re.sub(r'[A-Z]\S+\s*', ' #NE# ', the_rest)
或
如果您只想匹配任何语言的单词字符,请使用regex模块
regex.sub(r'[A-Z]\p{L}+\s*', ' #NE# ', the_rest)
因为
\w+
或[\w]+
与重音字符不匹配。因此,它无法匹配这些词
您可以使用\S+
而不是\w+
re.sub(r'[A-Z]\S+\s*', ' #NE# ', the_rest)
或
如果您只想匹配任何语言的单词字符,请使用regex模块
regex.sub(r'[A-Z]\p{L}+\s*', ' #NE# ', the_rest)
有没有可能使用unicode符号来捕获字符范围?示例:[\xC0-\xE1]还是什么?我跑过去,它似乎不介意。。。您需要找到自己的范围,但这只是一个开始:)
希望这有帮助。您是否有可能使用unicode符号来捕获字符范围?示例:[\xC0-\xE1]还是什么?我跑过去,它似乎不介意。。。您需要找到自己的范围,但这只是一个开始:)
希望这有帮助。我知道
\w
与重音字符不匹配。什么是回避?啊,非空白字符。我知道\w
与重音字符不匹配。什么是代用字符?啊,非空白字符。我不知道为什么它不能替换La
?因为它需要跳过第一个单词,因此str.partition()
我不知道为什么它不能替换La
?因为它需要跳过第一个单词,因此str.partition()