我正在使用一个小函数来循环文件,以便任何连字符-
被破折号取代–
(替代键+0150)。
我使用的函数为相关问题的解决方案添加了一些正则表达式风格(如何自动替换多个文件的文本内容中的字符? https://stackoverflow.com/questions/44996829/how-to-replace-a-character-inside-the-text-content-of-many-files-automatically)
def mychanger(fileName):
with open(fileName,'r') as file:
str = file.read()
str = str.decode("utf-8")
str = re.sub(r"[^{]{1,4}(-)","–", str).encode("utf-8")
with open(fileName,'wb') as file:
file.write(str)
我使用了正则表达式[^{]{1,4}(-)
因为搜索实际上是在乳胶回归表上执行的,我只想替换数字周围出现的连字符。
需要明确的是:我想替换所有连字符EXCEPT如果我们有真正的乳胶代码,例如\cmidrule(lr){2-4}
.
我表中的典型行是
variable & -2.061\sym{***}& 4.032\sym{**} & 1.236 \\
& (-2.32) & (-2.02) & (-0.14)
但是,我的正则表达式似乎不正确。例如,一个(-1.2)
将被替换为–1.2
,去掉括号。
这里有什么问题?
谢谢!
我可以提供以下两步更换:
str = "-1 Hello \cmidrule(lr){2-4} range 1-5 other stuff a-5"
str = re.sub(r"((?:^|[^{])\d+)-(\d+[^}])","\\1$\\2", str).encode("utf-8")
str = re.sub(r"(^|[^0-9])-(\d+)","\\1$\\2", str).encode("utf-8")
print(str)
第一个替换目标是所有不属于 LaTex 形式的范围{1-9}
即不包含在花括号内。第二个替换目标是所有前面带有非数字或字符串开头的数字。
Demo http://rextester.com/BQSZU45141
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)