这个问题要考虑到需要还原python代码原有的空格和缩进:
import keyword
import re
def rewrite_python_file(input_file, output_file):
with open(input_file, 'r') as source, open(output_file, 'w') as target:
pat = '[a-zA-Z]+'
for line in source:
new_line = ''
start = 0
lst = re.findall(pat,line)
for word in lst:
# 找到单词在原始行中的位置
start = line.find(word, start)
end = start + len(word)
# 如果单词不是保留字,则将其转换为大写
if not keyword.iskeyword(word) and word.islower():
word = word.upper()
# 将单词及其前面的空格添加到新的行中
new_line += line[len(new_line):start] + word
start = end
# 将剩余的部分添加到新的行中
new_line += line[len(new_line):]
target.write(new_line)
# 使用方法
rewrite_python_file('source.py', 'target.py')
在keyword模块中的kwlist保留字:
kwlist = [
'False',
'None',
'True',
'and',
'as',
'assert',
'async',
'await',
'break',
'class',
'continue',
'def',
'del',
'elif',
'else',
'except',
'finally',
'for',
'from',
'global',
'if',
'import',
'in',
'is',
'lambda',
'nonlocal',
'not',
'or',
'pass',
'raise',
'return',
'try',
'while',
'with',
'yield'
]
但是还是会出现执行不了的情况,比如导入模块的名字、以及print这些非保留字等,大写之后解释器是无法识别的。。。