2012-07-18 27 views
0

这是我第一天使用python并被卡住了。我有哪些内容看起来是这样的文件:在python中获取第一个数字字符串

  • 宣言//跳过
  • 富吧//显示为选项
  • 标签//跳过
  • 1 FOO
  • 2富
  • 3 bar
  • 4 foo bar
  • ...
  • 23546 477吧吧吧吧富

如果用户选择富,我只是想回到1,2,4和23546477,并在文件中写:

  • 目标1
  • 目标2
  • 目标4
  • 目标23546477

这就是我想出迄今:

import sys 
import re 

def merge(): 

    if (len(sys.argv) > 1): 
    labfile = sys.argv[1] 
    f = open(labfile, 'r') 
    f.readline() 
    string = f.readline() 
    print "Possible Target States:" 
    print string 
    var = raw_input("Choose Target States: ") 
    print "you entered ", var 
    f.readline() 
    words = var.split() 
    for line in f.readlines(): 
     for word in words: 
     if word in line: 
      m = re.match("\d+", line) 
      print m 
      //get the first number and store it in a list or an array or something else 

    f.close() 

merge() 

不幸的是它不工作 - 我看到像<_sre.SRE_Match object at 0x7fce496c0100>这样的行,而不是我想要的输出。

+0

什么不起作用?它是否引发异常?你得到了什么? – mgilson 2012-07-18 15:30:58

+0

尝试re.find而不是re.match – 2012-07-18 15:31:09

+4

* How does not work?它是否会抛出异常?产生错误的结果?穿着红色披肩穿过门口喊道:“没有人期待西班牙宗教裁判所!”? – 2012-07-18 15:31:55

回答

1

你想要做的(至少):

if m: #only execute this if a match was found 
    print m.group() #m.group() is the portion of the string that matches your regex. 
+0

好了现在我有我的号码... thx – MindlessMaik 2012-07-18 15:35:34

0

看那documentation - re.match返回匹配的对象,也就是你看到的。 re.findall会给你一个匹配给定行中的模式的字符串列表。

得到公正第一,你要使用匹配的对象,但你要re.search not re.match,然后你需要调用m.group()得到匹配的字符串进行匹配的对象。

相关问题