如果该行包含“";“一词?”;?用python

如果该行包含“";“一词?”;?用python,python,parsing,Python,Parsing,我有一个像这样的输入文件 test.txt CAT 396 NUM 59 X Y 4.7642 28.4443 4.7643 28.3640 6.2216 29.0680 6.2217 29.2841 6.4080 28.6427 6.6484 28.6484 CAT 397 NUM 592 X Y 7.0442 23.8

我有一个像这样的输入文件

test.txt
CAT 396 NUM 59 
X          Y     
4.7642     28.4443    
4.7643     28.3640    
6.2216     29.0680    
6.2217     29.2841    
6.4080     28.6427    
6.6484     28.6484    

CAT 397 NUM 592 
X          Y          
7.0442     23.8320    
7.0994     25.9161    
7.0995     25.1801    
我只需要X和Y坐标信息

我怎么才能只得到坐标呢

line = 'some words'
if 'word' in line:
    # skip/delete the line
如果要跳过的行始终是第一行,则可以跳过第一行,而不检查其中的单词

如果要跳过的行始终是第一行,您可以跳过第一行,而不检查其中的单词。

您可以尝试以下方法:

with open('test.txt') as fin :
    lines = fin.readlines()

coords = []
for line in lines :
    try :
        x, y = map( float, line.split())
        coords.append( (x,y) )
    except ValueError:
        pass  # ignore other lines
你可以试试这个:

with open('test.txt') as fin :
    lines = fin.readlines()

coords = []
for line in lines :
    try :
        x, y = map( float, line.split())
        coords.append( (x,y) )
    except ValueError:
        pass  # ignore other lines

您可以使用
readlines()[2:][/code>跳过前两行,然后解析数字。例如:像这样

test.txt
CAT 396 NUM 59 
X          Y     
4.7642     28.4443    
4.7643     28.3640    
6.2216     29.0680    
6.2217     29.2841    
6.4080     28.6427    
6.6484     28.6484    

CAT 397 NUM 592 
X          Y          
7.0442     23.8320    
7.0994     25.9161    
7.0995     25.1801    
lines=open('test.txt').readlines()[2:]
coords=[]
对于行中的行:
尝试:
追加(列表(映射(float,line.split()),行))
除值错误外:
打印(第{line}行中的f'ValueError)
打印(coords)
它返回:

[[7.0442, 23.832], [7.0994, 25.9161], [7.0995, 25.1801]]

您可以使用
readlines()[2:][/code>跳过前两行,然后解析数字。例如:像这样

test.txt
CAT 396 NUM 59 
X          Y     
4.7642     28.4443    
4.7643     28.3640    
6.2216     29.0680    
6.2217     29.2841    
6.4080     28.6427    
6.6484     28.6484    

CAT 397 NUM 592 
X          Y          
7.0442     23.8320    
7.0994     25.9161    
7.0995     25.1801    
lines=open('test.txt').readlines()[2:]
coords=[]
对于行中的行:
尝试:
追加(列表(映射(float,line.split()),行))
除值错误外:
打印(第{line}行中的f'ValueError)
打印(coords)
它返回:

[[7.0442, 23.832], [7.0994, 25.9161], [7.0995, 25.1801]]

您是将文件解析为csv还是手动解析?那么,您要做什么呢?您能够打开文件并移动每一行吗?这在python文档中有很好的文档记录。到目前为止,您应该展示您的代码,而不是要求在internet上记录了一百万次的东西,包括python文档。看看partition()函数。您是将文件解析为csv还是手动解析?那么,您要做什么呢?您能够打开文件并移动每一行吗?这在python文档中有很好的文档记录。到目前为止,您应该展示您的代码,而不是要求在internet上记录了一百万次的东西,包括python文档。看看partition()函数。谢谢!!这就是我想做的谢谢!!这就是我想做的it@lenik对,应该处理。编辑了我的代码。@lenik对,应该处理它。编辑了我的代码。