簡體   English   中英

如何使用python讀取特定行並在此行中打印特定位置

[英]how to read a specific line and print a specific position in this line using python

如何從文本文件中讀取特定行,該文本文件包含幾行具有相同字符“!”的行。 我的目標是找到最后一行並打印位置編號四“ [4]”。

我的file.txt:

     1.0000   1.0000   1.0000   1.0000   1.0000   1.0000   1.0000   1.0000
     1.0000   1.0000   1.0000   1.0000   1.0000   1.0000   1.0000   1.0000
     1.0000   1.0000   1.0002   0.9879   0.8682   0.6437  -0.0000  -0.0000
.
.
.
.
!    T   E              =    -122.1058
.
.
.
!    T   E              =    -123.1050
.
.
.
!    T   E              =    -125.10584323 

我的腳本(不起作用):

import sys, os
import datetime
import time as t

oTE_list = []
oTE = []

with open("file.txt","r") as f:
    text = f.readlines()
for line in text:
  if line[0] == '!':
    oTE_list.append(line[4])


# Change Lists To Number Format
for item in oTE_list:
  oTE.append(float(item))


for idx, item in enumerate(oTE_list):        
    if idx == len(oTE_list) - 1:
        print(item)
number5 = (item)

另一方面,我使用bash進行管理:

grep ! file.txt | awk 'END{print $5}'

結果應該是這樣的: -125.10584323

謝謝。

它很簡單,我不知道您為什么要復雜它。

f = open("file.txt", "r")
lines = [line for line in f.readlines() if line[0]=="!"]
number = float(lines[-1].split()[4])

說明:
f.readlines()讀取所有行f.readlines()
lines是以!開頭的行的列表!
lines[-1]從列表中選擇最后一行。
lines[-1].split()將在最后一行中列出單詞。 (在" " (空格)處分割)
lines[-1].split()[4]將從單詞列表中選擇第5個單詞。
float(lines[-1].split()[4])會將單詞轉換為float。

我認為您在這里尋找的是如何切割和切片琴弦 我已經對您上面提供的代碼進行了調整,以包括此字符串片段。 查看第一個for循環:-)

def main():
    oTE_list = []
    oTE = []

    with open("file.txt","r") as f:
        text = f.readlines()
    for line in text:
        if line[0] == '!':
            equals_index = line.index('=')
            # Get everything after the equal and remove extra whitespace
            after_equal = line[equals_index+1:].strip()
            oTE_list.append(after_equal)

    # Change Lists To Number Format
    for item in oTE_list:
        oTE.append(float(item))

    for idx, item in enumerate(oTE_list):
        if idx == len(oTE_list) - 1:
            print(item)


if __name__ == '__main__':
    main()

運行這個我得到結果:

C:\Python35\python.exe C:/Users/Frito/GitSource/help/sample.py
-125.10584323

現在您可能想知道這是如何工作的。 您輸入的內容有點困難,因為我知道並沒有消除其中所有空格的好方法! TE=<number>字段。 在這種情況下,通過查看您的數據,我選擇查找等號,然后僅查看其后的數據。 equals_index = line.index('=')查找字符串中等號所在的位置。 該“位置”包括空格。 通過查看字符串的位置24可以看到這一點。例如print(line[24])

現在我們可以計算等號在哪里,然后可以得到等號后的所有內容。 在您的示例中,這是您希望打印到屏幕上的數字,帶有一些額外的空格。 如果要使用print命令直接打印字符串“ abc”,它將在abc之前和之后以三個空格打印。 python中的.strip()函數刪除了這些多余的空格。

當我們結合以上兩種方法時,我們可以找到您的號碼並僅打印該號碼。 我希望這有幫助!

考慮到要打印的行,這甚至更簡單

#!/usr/bin/python
#import re
with open("file1.txt") as f:
  lines = f.readlines()[-1]
  lastline = lines.split()[-1]
  print lastline

期望的產出

bash-4.1$ ./file1.py
-125.10584323

如果您希望所有以"!"開頭的行 定位到最后一個索引值,然后可以在下面使用...。

#!/usr/bin/python
import re
with open("file1.txt") as f:
  lines = f.readlines()
  for line in lines:
    if "!" in line:
      line = line.split()[-1]
      print line

輸出值將為beow ..

bash-4.1$ ./file1_dup.py
-122.1058
-123.1050
-125.10584323

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM