2013-08-25 53 views
0

嗯,我有一个txt文件排序电话簿, 我想要做的是找到所有使用此模式例如数字829-2234和5号附加到开头的号码。添加前缀字符串的文件

所以结果现在变成5829-2234。

我的代码是这样开始的:

import os 
import re 
count=0 

#setup our regex 
regex=re.compile("\d{3}-\d{4}\s"} 

#open file for scanning 
f= open("samplex.txt") 

#begin find numbers matching pattern 
for line in f: 
    pattern=regex.findall(line) 
    #isolate results 
    for word in pattern: 
     print word 
     count=count+1 #calculate number of occurences of 7-digit numbers 
# replace 7-digit numbers with 8-digit numbers 
     word= '%dword' %5 

以及我真的不知道该怎么附加前缀5,然后用覆盖7位数号码的7位号码5前缀。我尝试了一些事情,但都失败了:/

任何提示/帮助,将不胜感激:)

感谢

+0

“附加前缀”是矛盾的。 – EJP

回答

4

就快,但你有你的字符串格式化走错了路。正如你知道,5永远是字符串(因为你要添加的话),你这样做:

word = '5%s' % word 

注意,你也可以使用字符串连接在这里:

word = '5' + word 

,甚至使用str.format()

word = '5{}'.format(word) 
+0

感谢的人! :) 简单有效 – scandalous

1

如果你使用正则表达式做它然后使用re.sub

>>> strs = "829-2234 829-1000 111-2234 " 
>>> regex = re.compile(r"\b(\d{3}-\d{4})\b") 
>>> regex.sub(r'5\1', strs) 
'5829-2234 5829-1000 5111-2234 '