我有一个使用xml模式的文件。看起来是这样的:
<maplayer simplifyAlgorithm="0" minimumScale="0" maximumScale="2500" simplifyDrawingHints="0" readOnly="0" minLabelScale="0" maxLabelScale="1e+08" simplifyDrawingTol="1" geometry="Point" simplifyMaxScale="1" type="vector" hasScaleBasedVisibilityFlag="1" simplifyLocal="1" scaleBasedLabelVisibilityFlag="0">
<id></id>
<datasource>port=1521 user=test_user password=test_passwd</datasource>
<keywordList>
<value></value>
</keywordList>
<featformsuppress>0</featformsuppress>
<editorlayout>generatedlayout</editorlayout>
<widgets/>
<conditionalstyles>
<rowstyles/>
<fieldstyles/>
</conditionalstyles>
</maplayer>
</projectlayers>
<properties>
<Variables>
<variableNames type="QStringList">
<value>paswd</value>
<value>user</value>
</variableNames>
<variableValues type="QStringList">
<value>5zdgf</value>
<value>dgdgdgfdg</value>
</variableValues>
</Variables>
<customproperties>
<property key="labeling/textColorR" value="0"/>
<property key="labeling/textTransp" value="0"/>
<property key="labeling/upsidedownLabels" value="0"/>
<property key="labeling/useSubstitutions" value="false"/>
<property key="labeling/wrapChar" value=""/>
<property key="labeling/xOffset" value="0"/>
<property key="labeling/yOffset" value="0"/>
<property key="labeling/zIndex" value="0"/>
<property key="variableNames"/>
<property key="variableValues"/>
</customproperties>
所以我想用python来研究密码和用户部分以及变量部分。 我使用以下代码:
import re
with open('C:\myfile.txt') as oldfile, open('C:\myfile_withoutPW.txt', 'w') as newfile:
oldText = oldfile.read()
noPass = re.sub(r'(password=).*?(?=\s) ', '', oldText.rstrip())
noPass_noUser = re.sub(r'(user=).*?(?=\s) ', '', noPass.rstrip())
# fehlt noch
newText = re.sub(re.escape(r'<property key="variableNames"/>'), '', noPass_noUser.rstrip())
newText = re.sub(re.escape(r'<property key="variableValues"/>'), '', newText.rstrip())
newfile.write(newText)
这是可行的,但并不完全如我所希望的那样,它深入研究了各个部分,但留下了空行,如:
<property key="labeling/wrapChar" value=""/>
<property key="labeling/xOffset" value="0"/>
<property key="labeling/yOffset" value="0"/>
<property key="labeling/zIndex" value="0"/>
</customproperties>
<blendMode>0</blendMode>
<featureBlendMo
我怎样才能解决这个问题,从我的txt文件中完整地钻研这些行/部分?你知道吗
用regex处理xml是有风险的。假设一个属性元素位于多行上。另一种方法是使用可扩展样式表转换(XSLT)。我不知道你的所有要求,所以我试着与你的例子相匹配:
这似乎对输出是可行的
Demo,,,其中新行
\n
被添加到正则表达式的某些部分,以便avoid creating empty line
。你知道吗在python中,可能是这样的
如果您想通过删除匹配的字符串来创建
remove empty lines
,那么您可以尝试使用这个正则表达式来匹配文本中的空行。你知道吗因此,通过插入这一行,它适用于您的脚本。你知道吗
相关问题 更多 >
编程相关推荐