自学内容网 自学内容网

python实例练习00001:使用正则表达式获取文件内容

print('Hello World!')
import re
try:
    file = input('enter the file :')
    with open(file, 'r') as f:
       data = f.read()
except FileNotFoundError:print(f'the file {file} does not exists:')

# 定义正则表达式
pattern = r"num (\d+) name (\w+) class (\d+) age (\d+)"
# 使用正则表达式提取数据
match = re.search(pattern, data)
if match:
    print('the first matching data')
    num = match.group(1)
    name = match.group(2)
    class_num = match.group(3)
    age = match.group(4)
    print(f"num={num}, name={name}, class={class_num}, age={age}")
else:
    print('no match')

matchs = re.findall(pattern, data)
# 打印结果
if matchs:
    print('\n\nall matching data')
    for match in matchs:
        num = match[0]
        name = match[1]
        class_num = match[2]
        age = match[3]
        print(f"num={num}, na

原文地址:https://blog.csdn.net/tankeven/article/details/140452267

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!