[英]how to remove the line if it contain the “word”? in python
我有一個輸入文件看起來像這樣
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 坐標信息。
我怎么能只得到坐標?
你可以試試這個:
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
line = 'some words'
if 'word' in line:
# skip/delete the line
如果要跳過的行始終是第一行,則可以跳過第一行,而不檢查其中的單詞。
您可以使用readlines()[2:]
跳過前兩行,然后解析數字。 例如:像這樣
lines = open('test.txt').readlines()[2:]
coords = []
for line in lines:
try:
coords.append(list(map(float, line.split())), lines))
except ValueError:
print(f'ValueError in line: {line}')
print(coords)
它返回:
[[7.0442, 23.832], [7.0994, 25.9161], [7.0995, 25.1801]]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.