开发者

string as array in python

开发者 https://www.devze.com 2023-03-16 12:25 出处:网络
I amnew learner in python.I need to make the following string as array. [\'Soyuz_TMA-16\', \'2009-09-30\']

I am new learner in python.I need to make the following string as array.

['Soyuz_TMA-16', '2009-09-30']
['Soyuz_TMA-17', '2009-12-20']
['Soyuz_TMA-01M', '2010-10-07']
.......
.....开发者_高级运维..
........

so that I can search in a text file for the string eg.['Soyuz_TMA-16', 2009-09-30'].If match together in some line eg:

    abcd 30th september 2009 skakk gkdka kkhhf Soyuz TMA 16.
    gfigka Soyuz TMA 16 hfkhf hghhg fghh 30th september 2009.

then it should return the whole line with marking the matches string.

Hopefully get a solution here.Thanks!


Parse the list of missions and dates into a dict missions, whose keys are the string value of dates: '2009-12-20'. Then, you can lookup the dict ('if date in missions: ...'). You'll also need to be able to parse the text-form of dates (using regex) into '2009-12-20' form, I wrote a function 'dtuple_to_date()'. (You could use a set rather than a dict, same idea. Looking up mapping types like dicts or sets is constant time i.e. O(1), rather than O(N) for a list of N elements.)

This code works:

import re

missions = """['Soyuz_TMA-16', '2009-09-30']
    ['Soyuz_TMA-17', '2009-12-20']
    ['Soyuz_TMA-01M', '2010-10-07']""".translate(None,',[]\'\"').split('\n')
missions = [t.split() for t in missions]

missions = dict((d,m) for m,d in missions)


input = """abcd 30th september 2009 skakk gkdka kkhhf Soyuz TMA 16.
gfigka Soyuz TMA 16 hfkhf hghhg fghh 30th september 2009.""".split('\n')


find_dates = re.compile(r'(\d+)\S*\s+(\S+)\s+(2008|2009|2010|2011)')

def dtuple_to_date(d,mth,y):
   """convert ('30','september','2009') to '2009-09-30"""
   m = {'january':1,'february':2,'march':3,'april':4,'may':5,'june':6,
        'july':7,'august':8,'september':9,'october':10,'november':11,
        'december':12}[mth.lower()]
   return "%s-%02d-%s" % (y,m,d)


for idx,line in enumerate(input):
    for (day,mth,yr) in find_dates.findall(line):
        date = dtuple_to_date(day,mth,yr)
        #print 'Looking up', date
        if date in missions:
            print 'Line %d: reference to mission %s on date %s' \
                % (idx, missions[date], date)
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号