Extract specified field value from filename using positional indexing

I have some filenames, and they each have data contained in them at specific locations in the string. I want a function that returns the value of the data specified by field. The doctest illustrates.

I'd like a nicer, easier-to-understand way to do this.

If possible, but secondarily, I'd like to be able to give the data in different types, according to which field they are, rather than just the string value.

def get_field_posn_list(field):     """List containing field position indices in filename"""     return({'place': [-11],             'year': range(-10, -7),             'session': [-6]}[field])   def get_field_str(fn, field):     """Get the string value of field stored in string fn     >>> get_field_str('/path/to/file/Z998-5.asdf', 'session')     '5'     """     val = ''.join([fn[i] for i in get_field_posn_list(field)])     return val 


This task is nearly equivalent to another recent question. My advice is that string analysis is usually best done using regular expressions.

import os
import re

def get_field_str(file_path, field):
    Get the string value of field stored in file_path

    >>> get_field_str('/path/to/file/Z998-5.asdf', 'session')
    pattern = re.compile('(?P<place>.)(?P<year>.{3})-(?P<session>.)\.')
    return pattern.search(os.path.basename(file_path)).group(field)

The regex can validate the filename as it works. Feel free to adjust it to match your expectations.

Category: python Time: 2016-07-30 Views: 0
Tags: python

Related post

  • Extracting exact field value from xml file and creating zip files based on each station type in unix using gzip 2013-10-30

    I have an xml file as below: <?xml version="1.0" encoding="UTF-8"?> <UnitReport Qunatity="163" start-time="2012-06-22T07:00:01+00:00"> <Station guid="59A7C775-7A2F-4ABD-BD10-B82614D5B846">

  • Extracting z values from shapefile using OGR Api 2014-06-29

    Is there an example of how we can extract the z value from a shp file given the x,y coordinate value (namely utm) using gdal/ogr c++ lib? alternatively, would it be easier if we convert the shp file into raster layer format and read off value from th

  • How to extract value from MongoDB using Node-RED? 2015-12-17

    I would like to extract value from MongoDB using Node-RED. Here in the below mentioned flow, RFID Reader running of Raspberry Pi reads RFID(ex:"badgeID":12) and produce value using MQTT, and same value is subscribe in Node-RED and this subscribe

  • In Rails, why can't I extract a specific value from a record using "where"? 2016-01-17

    I want to extract a specific value from a record. I can do this to just exctract the title of the article: x = Article.find(2) x.title But Why it gives an error when I do it like this x = Article.where(:id => 2) x.title I want to use "WHERE"

  • Passing a field value from a page to custom button 2014-07-18

    Here is the requirement: I have added a custom button on a standard Salesforce page. I want to pass a field value from this standard salesforce page to the button (or the pop up that opens up when the button is clicked). The scenario is similar to so

  • Get a field value from an nid 2012-05-11

    I have a large number of NIDs and I need one field value from each node. Is there any way to avoid the overhead of loading the entire node to get one field value? --------------Solutions------------- I don't think there's anything built in to the API

  • Get custom field value from not-current page 2010-11-01

    What is the best way of getting a custom field value from a page which is not the one currently displayed? I know the title of the page i want to get custom field value from, but not the pageID. Thanks! --------------Solutions------------- Use: $meta

  • How to copy Location Country field value from Parent object to Child object field default value? 2011-12-20

    I use Parent and Child content types with a Field used in both types. I would like Drupal to automatically propagate the Field value from Parent value to the Child field default value. How to do this ? I am interested specificaly in an example for Lo

  • Custom button to copy field values from other object 2014-02-13

    we have created an APEX class that creates a contract object from an opportunity object. We need to create a custom button on contract object to copy some field values from the related opportunity object to the new contract object and I do not really

  • set field value from function after user account edit/registering action 2014-06-04

    I need to assign one custom field value from user profile. One field is nickname (this field is filled by user) and I need to generate another field with function. The function takes nickname and using external library takes this nicknames ID. I need

  • How to transpose reclassified field values from one polygon shapefile to identical polygons of another shapefile? 2014-06-23

    I used vector output from modeling software as clip features for ecoregion input. I reclassified and dissolved the clipped layers into 3 subunits, and now would like to transpose those simplified values to the source ecoregion layer in areas of inter

  • Drupal 8: Read field value from $variables in preprocess_html 2015-03-11

    I've been wrestling with Drupal 8 for some time now and have run into a little problem. I want to get a field value from a content type that I can use in my html--front.html.twig. I can create a new variable that I can use in the twig template i.e $v

  • excluding non english field values from search_api index (or facet) 2015-04-08

    I have a CT product and a CT factory. Products have an entity reference field pointing to factories. I use node translation on factories (en, fr, de) but products are not translated (en only). Creating facet on the product's factory (entity reference

  • Get Grandchild Object Field Values from Parent Object 2015-06-16

    I'm a newbie at sales-force apex coding. I have 3 custom objects, Location(Parent) -> Group(child) - > Meeting(grand child). All are related to each other through Master detail relationships. I am trying to get 2 field values from the earliest Meeti

  • Extracting a Date value from a string 2016-01-20

    Forum. My code reads from an excel file and gets the following string in a variable 'textContainingDate': "Employee Filter: All Employees; Time Entry Dates: 01/07/2016-01/07/2016; Exceptions: All Exceptions" What I would like to do is extract th

  • How to extract these integer values from ArrayList String 2016-02-05

    This question already has an answer here: Cast Double to Integer in Java 13 answers I am having a ArrayList<String> abc in which I am getting this value [64.3, 25.1, 44.3, 34.2, 6.4, 48.5, 35.5, 59.5, 54.6, 26.6, 11.2, 50.3, 25.1] Now I want to extr

  • JRException: Error retrieving field value from bean: bornDate 2016-02-08

    This question already has an answer here: Unable to retrieve value from a JavaBean while generating reports using JasperReports API 1 answer bornDate is a java.util.Date field in my class, that is used to fill the collection represented by a List of

  • Extract Mean Raster Value from multiple raster files into Excel 2016-02-16

    I have a series of non-orthorectified raster files containing NDVI information. I would like to extract the mean value from each raster so I can see a summary of each raster image name and the corresponding mean NDVI pixel value for each one. I can a

  • How to extract the partition values from the cld() function in kml package 2016-02-16

    I am attempting to extract the partition values from the cld() function in kml package. The data is longitudinal (5 points) and from 7 tokens. When I use the cld() function, it gives me the partitions in a plot where I can see the lines (red and gree

iOS development

Android development

Python development

JAVA development

Development language

PHP development

Ruby development


Front-end development


development tools

Open Platform

Javascript development

.NET development

cloud computing


Copyright (C) avrocks.com, All Rights Reserved.

processed in 3.067 (s). 13 q(s)