![](/img/trans.png)
[英]How to find all capital and lower case occurrences of unicode character using regex and re.sub in Python?
[英]python: replacing a regular character with an unicode one using regex re.sub
我有一个简单的问题使我发疯,这似乎是由于unicode
字符在python中的处理所致。
我在磁盘上存储了latex
表(非常类似于http://www.jwe.cc/downloads/table.tex ),并且我想在其上应用一些正则表达式,以便将连字符-
( \−
)替换为en –
破折号–
( alt 0150
或\–
)
我正在使用以下函数来执行两个不同的正则表达式和替换。
import re
import glob
def mychanger(fileName):
with open(fileName,'r') as file:
str = file.read()
str = str.decode("utf-8")
str = re.sub(r"((?:^|[^{])\d+)\u2212(\d+[^}])","\\1\u2013\\2", str).encode("utf-8")
str = re.sub(r"(^|[^0-9])\u2212(\d+)","\\1\u2013\\2", str).encode("utf-8")
with open(fileName,'wb') as file:
file.write(str)
myfile = glob.glob("C://*.tex")
for file in myfile: mychanger(file)
不幸的是,这并没有改变任何东西。
但是,如果我使用$
之类的非unicode字符而不是\–
,它会\–
,这意味着正则表达式代码正确。
我在这里迷路了,我尝试使用re.sub(ur"((?:^|[^{])\\d+)\−(\\d+[^}])","\\\\1\–\\\\2", str).encode("utf-8")
但仍然不会更改任何内容。
怎么了 谢谢!
您的示例文件实际上包含HYPHEN-MINUS
(U + 002D)而不是U + 2212。
即使它确实包含正确的字符,您也会遇到Python 2.x Unicode的所有n00b问题:
\−
) r
raw修饰符 我的建议是删除所有解码和编码,并允许Python为您完成。 io
模块向后移植Python 3.x行为并为您解码文件。 我还将str
重命名为my_str
以避免与Python自己的str
类冲突。
import re
import glob
import io
def mychanger(fileName):
with io.open(fileName,'r', encoding="utf-8") as file:
my_str = file.read()
my_str = re.sub(u"((?:^|[^{])\d+)\u002d(\d+[^}])", u"\\1\u2013\\2", my_str)
my_str = re.sub(u"(^|[^0-9])\u002d(\d+)", u"\\1\u2013\\2", my_str)
with io.open(fileName, 'w', encoding="utf-8") as file:
file.write(my_str)
myfile = glob.glob(C://*.tex")
for file in myfile: mychanger(file)
有关Python 2.x和Unicode的完整说明,请参见如何解决:“ UnicodeDecodeError:'ascii'编解码器无法解码字节”
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.