Problem:我试图用Python中的另一个浮点表示的多个特定序列替换字符串中的多个特定序列.
我在JSON文件中有一个字符串数组,我通过JSON模块将其加载到python脚本中.
{
"LinesToReplace": [
"_ __ ___ ____ _____ ______ _______ ",
"_._ __._ ___._ ____._ _____._ ______._ ",
"_._ _.__ _.___ _.____ _._____ _.______ ",
"_._ __.__ ___.___ ____.____ _____._____ ",
"_. __. ___. ____. _____. ______. "
]
}
我通过JSON模块加载JSON文件:
with open("myFile.json") as jsonFile:
data = json.load(jsonFile)
我试图用浮点表示的特定子字符串替换_
的序列.
Specification:
- 要在字符串中查找的字符必须是单个
_
或多个_
的序列. -
_
序列的长度未知. - 如果单个
_
或多个_
的序列后面紧跟着一个.
,然后又紧跟着一个_
或多个_
的序列,则_
序列中的.
is part. -
.
用于指定小数 - 如果
.
后面没有一个_
或多个_
的序列,则.
是_
序列的is not part. - 将
_
和.
的序列替换为浮点表示,即%f1.0
. - 表示取决于
_
和.
序列.
Examples:
-
__
将被%f2.0
所取代. -
_.___
将被%f1.3
所取代. -
____.__
将被%f4.2
所取代. -
___.
将被%3.0
所取代.
对于上述JSON文件,结果应该是:
{
"ReplacedLines": [
"%f1.0 %f2.0 %f3.0 %f4.0 %f5.0 %f6.0 %f7.0 ",
"%f1.1 %f2.1 %f3.1 %f4.1 %f5.1 %f6.1 ",
"%f1.1 %f1.2 %f1.3 %f1.4 %f1.5 %f1.6 ",
"%f1.1 %f2.2 %f3.3 %f4.4 %f5.5 ",
"%f1.0. %f.0. %f3.0. %f4.0. %f5.0. %f6.0. "
]
}
一些代码,试图用%f1.0
代替单个_
(这不起作用…):
with open("myFile.json") as jsonFile:
data = json.load(jsonFile)
strToFind = "_"
for line in data["LinesToReplace"]:
for idl, l in enumerate(line):
if (line[idl] == strToFind and line[idl+1] != ".") and (line[idl+1] != strToFind and line[idl-1] != strToFind):
l = l[:idl] + "%f1.0" + l[idl+1:] # replace string
有什么办法吗?我也想过如何使用正则表达式.