37,743
社区成员




# coding=utf-8
import re
import keyword
with open('testsource.py', encoding='utf-8') as f:
s = f.read()
s = s.upper()
#define keywords by yourself, e.g. attributes from print: 'end', re: 'flags', module name: 're', etc.
my_keywords = ['end', 'flags', 're']
keys = keyword.kwlist + dir(__builtins__) + my_keywords
for k in keys:
s = re.sub(k, k, s, flags=re.IGNORECASE)
with open('testwrite.py','w', encoding='utf-8') as fw:
fw.write(s)
1. 用正则的sub而不用 str.replace , 是因为有时候替代有重叠,必须忽略大小写去查找。例如: 先替代 for后, 所有FORMAT就变成了forMAT
2. 加入了一个自定义的关键字列表,是因为有些函数的属性的名字没有在关键字列表中,比如 print 函数中的 end (print(a, end=''), 上面的re 中的 ‘flags’, 模块名字如‘math’等
3. 关键字要保持原样,例如‘False’, 'True', 'None' 等有大小写混合
测试了你上面的两文件都没问题。
需要进一步开发:
1. 完善属性和模块名字等其他关键字
2. 判定是否是 注释,因为注释中如有单词和关键字一样,也会改成小写的
3. ....