【问题标题】:Retrieve specific lines from ASCII files using Python使用 Python 从 ASCII 文件中检索特定行
【发布时间】:2022-01-18 13:23:05
【问题描述】:

我正在使用ESM(工程强运动数据库)上的地震数据,我需要从每个地震站下载每次地震的特定参数。我目前正在手动执行此操作,但需要一段时间,我想改用 Python。

在上面提供的链接中,我选择加速数据并导出。但是,不是一个包含所有信息的文件,而是下载每个单独的 ASCII 文件(例如,如果有 326 条记录,则将下载 326 个单独的文件)。

我想找到一种方法将所有记录下载到一个文件中,我认为这是不可能的,或者使用 Python 从每个 ASCII 文件中检索特定行。这些将是“Network”、“Station_Code”、“Station_Name”、“Station_Latitude_Degree”、“Station_Longitude_Degree”和“PGA_CM/S^2”。有没有办法只检索这些行,然后自动将它们导出到包含所有数据的文件中?

谢谢,利亚姆

【问题讨论】:

    标签: python python-3.x list web-scraping


    【解决方案1】:

    这个脚本可能会有所帮助!我假设所有 .ASC 文件都在一个名为“input_files”的文件夹中,该文件夹与脚本位于同一目录中!您可以在以下脚本的第 3 行中更改所有 .ASC 文件所在文件夹的路径。

    import os
    
    input_dir = "input_files"
    output_file = "all_data.txt"
    
    output_lst = []
    def process_file(filepath):
      interesting_keys = (
        'Network',
        'Station_Code',
        'Station_Name',
        'Station_Latitude_Degree',
        'Station_Longitude_Degree',
        'PGA_CM/S^2'
      )
    
      with open(filepath) as fh:
        content = fh.readlines()
        for line in content:
          line = line.strip()
          if ":" in line:
            key, _ = line.split(":", 1)
            if key.strip() in interesting_keys:
              output_lst.append(line)
    
    def write_output_data():
      if output_lst:
        with open(output_file, "w") as fh:
          fh.write("\n".join(output_lst))
          print("See", output_file)
    
    def process_files():
      for filepath in os.listdir(input_dir):
        process_file(os.path.join(input_dir, filepath))
    
      write_output_data()
    
    process_files()
    

    【讨论】:

    • 感谢您的帮助!
    【解决方案2】:

    这是一个有趣的,请参阅下面的脚本,它会下载所有原始数据。我已按要求提取了关键数据,但您可能想自己查看原始数据,因为那里有很多。

    需要注意的是,我能找到的唯一“PGA_CM/S^2”数据是每条记录的“开始”页面上的粗体值。

    import requests
    import pandas as pd
    
    url = 'https://esm-db.eu/esm_next_ws/jsonrpc'
    payload = '{"jsonrpc":"2.0","method":"armonia","id":"8","params":{"map":{"_page":"DYNA_X_event_waveform_band_instrument_D","_state":"find","_action_json_rpc_list":"1","_rows_per_page":"10000","internal_event_id":"IT-2012-0008","_operator_internal_event_id":"=","_order_field_0":"epi_dist","_order_direction_0":"asc","_token":"NULLNULLNULLNULL"}}}'
    con_len = len(payload)
    
    headers= {
        'Accept':'application/json, text/plain, */*',
        'Accept-Encoding':'gzip, deflate, br',
        'Content-Length':str(con_len),
        'Content-Type':'application/x-www-form-urlencoded',
        'Host':'esm-db.eu',
        'Origin':'https://esm-db.eu',
        'Referer':'https://esm-db.eu/',
        'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36'
        }
    
    
    print('Fetching data...')
    data = requests.post(url,headers=headers,data=payload).json()
    
    final = []
    for row in data['result']['rows']:
    
        #loads of data, might be worth downloading json (data variable) and seeing what else you want
    
        item = {
        'Network':row[39],
        'Station_Code':row[22],
        'Station_Name':row[46][10],
        'Station_Latitude_Degree':row[46][12],
        'Station_Longitude_Degree':row[46][3],
        'PGA_CM/S^2':row[18], #can only find the value in bold on the "Go" page
        'Date':row[24].replace('T',' '),
        }
    
        final.append(item)
    df = pd.DataFrame(final)
    
    df.to_csv('earthquakedata.csv',index=False)
    print('Saved to earthquake.csv')
    

    如果您想要整个数据负载(在 csv 中几乎无法管理),那么您可以通过将最后几行更改为以下内容将其全部转储到 csv:

    print('Fetching data...')
    data = requests.post(url,headers=headers,data=payload).json()
    
    df = pd.DataFrame(data['result']['rows'])
    
    df.to_csv('earthquakedata_ugly.csv',index=False)
    print('Saved to earthquake_ugly.csv')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-31
      • 1970-01-01
      • 2021-01-25
      • 1970-01-01
      • 2013-08-25
      • 1970-01-01
      • 2018-08-16
      • 1970-01-01
      相关资源
      最近更新 更多