【问题标题】:Find a string in a text file, and then print the first words of the following lines in Python在文本文件中查找一个字符串,然后在 Python 中打印以下行的第一个单词
【发布时间】:2015-05-28 03:31:33
【问题描述】:

我正在尝试在文本文件中查找关键字。然后,打印以下 3 行的前 3 个单词。

这是我的文本文件的一个例子:

...
NAME SP IPHASW D HRMM SECON ...
ABCD BH YZ     A 1236 53.70
EFGH BH XH     A 1243 56.80 
IJKL SZ TU     B 1248 32.30
MNOP SZ RT       1252 18.50
QRST BH DF     B 1253 54.40

所以,我想找到字符串:“NAME”,然后打印下面的“ABCD”、EFGH”和“IJKL”。

这是我的 Python 代码:

sfile=open("file.txt")

while True:

  line = sfile.readline()

  if line.startswith('NAME'):       
    item1 = sfile.readline()[0:4]
    item2 = sfile.readline()[0:4]
    item3 = sfile.readline()[0:4]
    break


sfile.close()

但它不起作用......

对此的任何帮助将不胜感激!谢谢 :)

【问题讨论】:

  • 你需要python吗? grep '^NAME' yourfile --after-context=3
  • 我相信您正在寻找 print 关键字。
  • 好吧,我正在用 Python 编写所有程序!当然,我使用 print 关键字,但在关闭文件之后。
  • 这些文本文件可以有多大?
  • 最大大小约40行

标签: python


【解决方案1】:

您需要采取的第一步是将文本文件转换为合适的数据结构,我为这个问题选择了字典,您也可以使用嵌套列表。

其次,我将各个列的名称转换为该字典的键,然后将这些列下的行值分配为该键的值。

dictionary = {}
with open("sample.txt") as sfile:
    data = sfile.readlines()
    keys = data[0].split()
    for k in keys:
        #For creating an empty dictionary
        dictionary[k] = []
    for values in data[1:]:
        for i,value in enumerate(values.strip().split()):
            dictionary[keys[i]].append(value)
    #print dictionary #To review the data structure.

keyword = "NAME"#raw_input("Please enter the keyword:")
print dictionary[keyword][:3]

【讨论】:

    【解决方案2】:

    这行得通,不知道是不是你要找的。​​p>

    with open("file.txt", 'r') as sfile:
    
      lines = sfile.read()
      rows = lines.split('\n')
    
      for columns in rows:
        items = columns.split(' ')
        print items[0]
    

    【讨论】:

    • 这是个好主意!现在如果我想创建一个数组,这样可以更容易找到我要查找的单词!
    【解决方案3】:

    好的,我的问题已经解决了!

    这是我的解决方案:

      sfile=open("file.txt")
      data_sfile=sfile.read()
      myArray = data_sfile.split('\n') 
    
      for i in range(len(myArray)):
            if myArray[i].find("NAME ")>=0:
              item1 = myArray[i+1]
              item2 = myArray[i+2]
              item3 = myArray[i+3]
              break
    
          item1 = item1 [0:5] 
          item2 = item2 [0:5] 
          item2 = item2 [0:5]
    
      sfile.close()
    

    好吧,这不是最漂亮的解决方案,但它有效!

    感谢您的回答

    【讨论】:

      猜你喜欢
      • 2020-02-01
      • 2012-08-10
      • 2021-12-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多