我最近从“Python Quick Book”中学到了一些关于 Python re 模块的知识。
我试图测试书中的代码。除了我的代码没有错误之外,它没有识别文件中给出的数据模式。
import re
regexp = re.compile(r"(?P<last>[-a-zA-Z]+)"
r"(?P<first>[-a-zA-Z]+)"
r" ( (?P<middle> ([-a-zA-Z]+)))?"
r": (?P<phone> (\d\d\d-)?\d\d\d-\d\d\d\d)"
)
file = open ('dir.txt', 'r')
for line in file.readlines():
result = regexp.search(line)
if result == None:
print ("Oops, I don't think this is a record")
else:
lastname = result.group('last')
firstname = result.group('first')
middlename = result.group('middle')
if middlename == None:
middlename = ''
phonenumber = result.group('phone')
print ('Name:', firstname, middlename, lastname, ' Number: ',phonenumber)
file.close()
这是我的文本文件中给出的数据。
Khan, Ahmed Ali : 800-123-4567
Malik, Asif Ali : 800-123-7844
Shaikh, Muhammad Sharafat: 300-123-4444
Shah, Farhat Abbas : 321-822-2977
Adam, Khalid Ahmed : 000-124-5454
提前致谢。:)