2015-06-27 44 views
0

我想從下面的字符串文本示例行解析出幾個數字和名稱。
該文件與下面的格式類似。如何提取並解析出字符串文本文件中的字符串字段

1. 00054 **/ 063076600 NAME** Days Off: 21 Cr:021:00 
2. CAPS ALLL +++ VSVS 
3. more lines of text 
4. 00054/063076600 NAME Days Off: 21 Cr:074:30 
5. CAPS ALLL +++ VSVS 
6. more lines of text.... 

我需要解析出「/」後面的數字(063076600)和名稱(NAME)。 包含這些字段的行始終包含前面的「/」。 NAME也在所有Caps中。 我嘗試使用str.isupper()作爲名稱字段,但很多我不需要的文本都是像第2行那樣的大寫,所以這不起作用。

有沒有什麼方法可以指定如何獲取「/」後面的2個項目並將它們添加到列表中?

fname =raw_input('Enter the filename:') 
listOfnames = [] 
try: 
    fhand = open(fname) 
except: 
    print 'File cannot be opened',fname 
    exit() 
count = 0 
with open(fname) as f: 
    for line in f: 
     # break line to words 
     for word in line.strip().split(): 
      if word.startswith('/'): 
      #get the number after "/" and append 
      #get the NAME and append 
       count = count + 1 
       listOfnames.append(word) 
       try: 
        print "number is", number 
        print "name is" , name 
       except: 
        print "not available" 
print listOfnames 
print 'count is',count 

回答

0
def handle_input(fhand): 
    listofnames = [] 
    count = 0 
    try: 
     with open(fhand,'r') as data: 
      for i in data: 
       if '/' in i: 
        number, name = filter (lambda x: x,i.split('/')[1].split(' '))[:2] 
        count += 1 
        listofnames.append([name,number]) 
     if listofnames: print 'count:{}\nnames:\n{}'.format(count,''.join(map(lambda x: "\t{}: {}\n".format(x[0],x[1]),listofnames))) 
    except Exception: 
     print 'not available' 

handle_input('test.txt') 

結果:

count:2 
names: 
    NAME: 063076600 
    NAME: 063076600 
+1

mitghi,非常感謝你對我的幫助與我一直在努力解決一個問題 – patches10