English 中文(简体)
正式表述代替职能包括太多案文
原标题:Regular expression replace function includes too much text
  • 时间:2011-11-04 00:12:28
  •  标签:
  • python
  • regex

I m a python newbie. My script (below) contains a function named "fn_regex_raw_date_string" that is intended to convert a "raw" date string like this: Mon, Oct 31, 2011 at 8:15 PM into a date string like this: _2011-Oct-31_PM_8-15_

Question No. 1: When the "raw" date string contains extraneous characters eg (xxxxxMon, Oct 31, 2011 at 8:15 PMyyyyyy), how should I modify my regular expression routine to exclude the extraneous characters?

  I was tempted to remove my comments from the script below to make it 
     simpler to read, but I thought it might be more helpful for me to leave 
     them in the script.

Question No. 2: I suspect that I should code another function that will replace the "Oct" in "2011-Oct-31_PM_8-15_ " with "11". But I can t help wondering if there is some way to include that functionality in my fn_regex_raw_date_string function.

Any help would be much appreciated.

Thank you, Marceepoo

import sys
import re, pdb
#pdb.set_trace()

def fn_get_datestring_sysarg():
    this_scriptz_FULLName = sys.argv[0]
    try:
        date_string_raw = sys.argv[1]
    #except Exception, e:
    except Exception:
        date_string_raw_error = this_scriptz_FULLName +  :  sys.argv[1] error:  No command line argument supplied 
        print date_string_raw_error
    #returnval = this_scriptz_FULLName +  
  + date_string_raw
    returnval = date_string_raw
    return returnval

def fn_regex_raw_date_string(date_string_raw):
    # Do re replacements
    # p:DataVBPython_MarcsPrgsPython_ItWorksFixCodeFromLegislaturezCalifCode_MikezCode.py
    # see also (fnmatch) p:DataVBPython_MarcsPrgsPython_ItWorksookmarkPDFs.aab.py

    #srchstring = r"(.?+)(Sun|Mon|Tue|Wed|Thu|Fri|Sat)(, )(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)( )([d]{1,2})(, )([d]{4})( at )([d]{1,2})(:)([d]{1,2})( )(A|P)(M)(.?+)"
    srchstring = r"(Sun|Mon|Tue|Wed|Thu|Fri|Sat)(, )(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)( )([d]{1,2})(, )([d]{4})( at )([d]{1,2})(:)([d]{1,2})( )(A|P)(M)"

    srchstring = re.compile(srchstring)    
    replacement = r"_7-3-5_13M_9-11_"
    #replacement = r"_8-4-6_14M_10-12_"    
    regex_raw_date_string = srchstring.sub(replacement, date_string_raw)

    return regex_raw_date_string

    # Mon, Oct 31, 2011 at 8:15 PM  
if __name__ ==  __main__ :
    try:
        this_scriptz_FULLName = sys.argv[0]
        date_string_raw = fn_get_datestring_sysarg()
        date_string_mbh = fn_regex_raw_date_string(date_string_raw)
        print date_string_mbh
    except:
        print  error occurred - fn_get_datestring_sysarg() 
问题回答

该法典使用一种固定的表述,取代整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整的整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整整

然后打电话datetime.strptime (date_str,date_format),其中做的是课堂的辛勤工作,并给我们一个datetime。 例如:

from datetime import datetime

import calendar
import re

# -------------------------------------

# _months = "|".join(calendar.month_abbr[1:])
_weekdays = "|".join(calendar.day_abbr)

_clean_regex = re.compile(r"""
    ^
    .*?
    (?=""" + _weekdays + """)
    |
    (?<=AM|PM)
    .*?
    $
""", re.X)

# -------------------------------------

def parseRawDateString(raw_date_str):
    try:
        date_str = _clean_regex.sub("", raw_date_str)
        return datetime.strptime(date_str, "%a, %b %d, %Y at %I:%M %p")

    except ValueError as ex:
        print("Error parsing date from  {} !".format(raw_date_str))
        raise ex

# -------------------------------------

if __name__ == "__main__":
    from sys import argv

    s = argv[1] if len(argv) > 1 else "xxxxxMon, Oct 31, 2011 at 8:15 PMyyyyyy"

    print("Raw date:        {} ".format(s))
    d = parseRawDateString(s)
    print("datetime object:")
    print(d)
    print("Formatted date:  {} ".format(d.strftime("%A, %d %B %Y @ %I:%M %p")))




相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...

热门标签