你好,我是python新手,我有这个简单的代码来替换文本。 一切正常,但我需要为 -DeviceMap“ 32” 替换 -Phsig 33 部分,并添加引号,并且编号要比以前少一个。它以某种方式容易吗?
CACHE_DRIVER=database
TXT文件样本:
import os
import shutil
os.chdir('C:\\konverze')
print(os.getcwd())
print (os.listdir())
shutil.copy2('C:\\konverze\EIO.CFG', 'C:\\konverze\EIO_konvertovane.CFG')
print ("kopírování File EIO.CFG bylo úspěšné")
s = open("EIO.CFG").read()
s = s.replace('-Unit', '-Device')
s = s.replace('-Type', '-SignalType')
s = s.replace('-Phsig', '-DeviceMap')
f = open("EIO_konvertovane.CFG", 'w')
f.write(s)
f.close()
所需结果:
-Name "diSPARE00" -Type "DI" -Unit "SIM_BOARD" -Phsig 1
-Name "doMotOnState" -Type "DO" -Unit "DP_BOARD" -Phsig 33\
-Access "System"
-Name "doService" -Type "DO" -Unit "DP_BOARD" -Phsig 44 -Access "All"
非常感谢您的建议
答案 0 :(得分:0)
这是您的方法:
...
dockedItems: [
{
xtype:'toolbar',
reference: 'tbar',
docked: 'top',
items: [{
text: 'Expand All',
handler:function()
{
me.expandAll()
me.resumeLayouts(true)
}
},{
text: 'Collapse All',
handler:function()
{
me.collapseAll()
console.log(me)
}
}]
},
{
xtype: 'textfield',
dock: 'top',
emptyText: 'Search',
enableKeyEvents: true,
....
分割文本以获得数组s.split(' ')
arr
添加引号w = '"' + w + '"'
来获取文本。答案 1 :(得分:0)
您可以将文本分成几行,然后在每一行中查找“ -DeviceMap”,然后在此之后替换为该数字,该数字减1并用"
包围
s = """\
-Name "diSPARE00" -Type "DI" -Unit "SIM_BOARD" -Phsig 1
-Name "doMotOnState" -Type "DO" -Unit "DP_BOARD" -Phsig 33\
-Access "System"
-Name "doService" -Type "DO" -Unit "DP_BOARD" -Phsig 44 -Access "All"\
"""
s = s.replace('-Unit', '-Device')
s = s.replace('-Type', '-SignalType')
s = s.replace('-Phsig', '-DeviceMap')
s = s.splitlines()
new_s = []
for line in s:
line = line.split(' ')
if '-DeviceMap' in line:
line[line.index('-DeviceMap')+1] = '"{}"'.format(int(line[line.index('-DeviceMap')+1]) - 1)
new_s.append(' '.join(line))
s = '\n'.join(new_s)
print(s)
输出:
-Name "diSPARE00" -SignalType "DI" -Device "SIM_BOARD" -DeviceMap "0"
-Name "doMotOnState" -SignalType "DO" -Device "DP_BOARD" -DeviceMap "32" -Access "System"
-Name "doService" -SignalType "DO" -Device "DP_BOARD" -DeviceMap "43" -Access "All"
如果在'Phsig'之后的单词中除小数点以外可能还有其他字符,您可以将它们替换为空,例如:
'33\\'.replace('\\', '') # -> '33'
因此,在最终代码中,我们将引发错误的行更改为:
line[line.index('-DeviceMap')+1] = '"{}"'.format(int(line[line.index('-DeviceMap')+1].replace('\\', '')) - 1)