繁体   English   中英

蟒蛇。 在文件中查找字符串

[英]python. finding a string within a file

背景:我正在尝试从tmx文件中读取文件,并试图在文件中查找特定的字符串。

我到目前为止的代码

import string 
mapName = "test.js"      
tmxmap = "map.tmx"           
n,y,t = 0,0,0             
with open (mapName, 'w') as f:           

with open (tmxmap, 'r') as f1:
    t_contents = f1.readlines()
    for line in t_contents: 
        if '<objectgroup' in line:
            n = t
        if '</objectgroup' in line: 
            y = t
        t = t + 1
    f1.seek(1)
    print (n,y)
    for i in range (n,y+1):
        #f.write (t_contents[i])
        for line in t_contents[i]:
            if "id" in line: 
                f.write(t_contents[i])
print ("done")
'

因此,您可以根据需要忽略代码的前半部分,因为这是我为获取文件的特定部分而编写的代码,但是在其中,您可以看到我可以在一行中搜索字符串。 上半年效果很好

但是,当我尝试在底部的“ if'id'in line”中执行相同操作时,该部分将不再起作用。 但是,当我在行中执行'if'i'时,该语句确实起作用。(仅一个字符,如果我在行中执行'if'x'也同样适用,因此我不确定问题出在哪里。

我试图读取的tmx文件的一部分是

<objectgroup name="Walls" visible="0">
<object id="2" x="210" y="145" width="93" height="95"/>
<object id="3" x="56" y="150" width="48" height="51"/>
<object id="5" x="184" y="117.5" width="48" height="51"/>
<object id="6" x="311" y="117.5" width="48" height="51"/>
<object id="7" x="727" y="21.5" width="48" height="51"/>
<object id="8" x="1207" y="565.5" width="48" height="51"/>
<object id="9" x="1240" y="598.5" width="48" height="51"/>
<object id="10" x="1144" y="982.5" width="48" height="51"/>
<object id="11" x="1177" y="1078.5" width="48" height="51"/>
<object id="12" x="984" y="1046.5" width="48" height="51"/>
<object id="13" x="833" y="643" width="414" height="315"/>
<object id="15" x="102" y="485" width="308" height="86"/>
<object id="16" x="421" y="485" width="438" height="86"/>
<object id="18" x="772.667" y="133.333" width="87.3333" height="436.667"/>
<object id="20" x="355" y="162" width="410" height="315"/>
<object id="21" x="759" y="662.5" width="48" height="51"/>
</objectgroup>

您的问题出在额外的循环中。 for line in t_contents[i]:的循环经过t_contents[i]每个元素。 由于t_contents[i]是字符串,因此其元素是单个字符,因此line始终是一个字符,并且只能等于另一个单个字符。 您需要摆脱一个循环:

for i in range (n,y+1):
#    for line in t_contents[i]:
        if "id" in t_contents[i]: 
            f.write(t_contents[i])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM