python查找文件中关键字并获取

python查找文件中关键字并获取

问题描述:

img


我的问题是如果一行里有多个关键词 他只会输出第一个,怎么解决

用正则表达式吧,匹配字符串的神器!!


import re

file = './in.c'
outfile = './out.txt'
with open(file, 'r', encoding='UTF-8') as f:
    f_read = f.read()

s = re.findall(r"if|else|while|switch|case", f_read, re.MULTILINE)

with open(outfile, 'w', encoding='UTF-8') as f:
    if s == []:
        f.write('No answer')
    else:
        for i in s:
            f.write(i)