COULD ANY GEEK HELP ME FIND OUT WHAT IS WRONG WITH MY CODE FOR RE?
SINCE THE BACK PART IS MARKED INVALID SYNTAX......

'''you are given  a bunch of phone
numbers in a file whose name is
provided by parameter name_fin,
each line has exectly one phone number.
They look like this:

8144658695
812 673 5748
812  453   6783
812-348 7584
(617) 536 6584
834-674-8595

use some regexes to reformat
the numbers using the sub() method
so that the phone numbers look like
814+465-8695
812+673-5748
812+453-6783
812+348-7584
617+536-6584
834+674-8595

and write back to a file whose name is provided
by parameter name_fout, each line with one
phone number, in the same order as in the input file.'''

HERE IS MY ANSWER O(∩_∩)O~

def phone_numbers(name_fin, name_fout):
  with open(name_fin,'rU') as f, open(name_fout,'wt') as g:
        s=[]# 先搞一个list来装 fin 的内容
        for line in f:
            line=line.rstrip('\n') # 现将每一行的换行符去掉
            x=compile(r'(\d{3})\D*(\d{3})\D*(\d{4})' )
            x.sub( r'\1+\2-\3', line )
            #将 fin 中每一行的内容先进行转换,分成三个部分
            s.append((x.sub( r'\1+\2-\3', line ))
            #再将每一行进行替换,换成题目要求的形式
            #第一部分和第二部分以'+'相连,第二部分和第三部分以'—'相连
        line ='\n'.join(s[i] for i in range(len(s))
        print(line,file=g)
        #将得到的s list 中的每一项,用换行符相连,而后输出到fout 里面(这里定义为g)

Add "import re" at the top of script and line 6 should be

x = re.compile(...)

Line 9 has 1 additional '('.

Line 12 can just be

line = '\n'.join(s)
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.