匹配一行后,如何读取更多行并记录值,然后重新开始?python
我想知道如何在文本文档中搜索单词POLYLINE,然后一旦找到它,如何在文本文档中继续搜索POLYLINE的更多属性,如x坐标和y坐标,然后找到下一条POLYLINE并再次执行 我有一个如下所示的文本文件: 多段线 废话 X坐标 五十 Y坐标 六十三 废话 废话 X坐标 九十 Y坐标 六 多段线 等等 到目前为止,我的代码所做的只是查找单词POLYLINE,我一直在尝试收集POLYLINE的属性。 以下是我目前的代码:匹配一行后,如何读取更多行并记录值,然后重新开始?python,python,loops,text-files,readline,doc,Python,Loops,Text Files,Readline,Doc,我想知道如何在文本文档中搜索单词POLYLINE,然后一旦找到它,如何在文本文档中继续搜索POLYLINE的更多属性,如x坐标和y坐标,然后找到下一条POLYLINE并再次执行 我有一个如下所示的文本文件: 多段线 废话 X坐标 五十 Y坐标 六十三 废话 废话 X坐标 九十 Y坐标 六 多段线 等等 到目前为止,我的代码所做的只是查找单词POLYLINE,我一直在尝试收集POLYLINE的属性。 以下是我目前的代码: import re fileName = open("textdoc.tx
import re
fileName = open("textdoc.txt, "r")
for line in fileName:
if re.match("POLYLINE", line):
print line
fileName.close()
我怎样才能解决这个问题
for line in fileName:
if re.match("POLYLINE", line):
for line in filename:
if re.match(xcoord,line):
dostuff()
if re.match(ycoord,line):
dostuff()
至于你如何找到坐标,我们很难用你提供的东西做任何事情。如果没有关于坐标将出现在哪一行的模式,或者如果有其他数字不是您的坐标,并且这些数字本身没有某种标识,那么您就无能为力。基本上,找到允许您将坐标与其他坐标区分开来的任何东西,然后搜索它。假设结构一致,您可以收集如下属性
#store polylines in a list for future use
polylines=[]
dataFile = open('textdoc.txt')
#collect the attributes in dictionaries
attrs={}
#because it appears you need to look one line ahead to get the coordinates
# it would be easiest to read all lines into a list
datalines = dataFile.readlines()
for idx, line in enumerate(datalines):
#handle polyline flags by storing the previous attributes
if 'POLYLINE' in line:
#attrs will evaluate to True if its not empty
if attrs:
#append the old polyline attributes and start a new one
polylines.append(attrs)
attrs = {}
continue
#collect the attributes from the line following the coord flag
# of course this breaks real fast if the file structure changes
if 'xcoord' in line:
#grab the coordinate from the following line
attrs['xcoord'] = datalines[idx + 1].strip()
continue
if 'ycoord' in line:
attrs['ycoord'] = datalines[idx + 1].strip()
continue