Skip to main content
 首页 » 编程设计

Python:将文本文件中的特定单词大写

2025年01月19日13daizhj

我正在尝试编写一个 python 脚本来格式化 SQL 代码以提高可读性。

例如。将特定的小写单词转换为大写:select -> SELECT

我正在尝试使用 Python 中的读写功能来执行此操作。但是,我被卡住了。这是我的代码:

words = ['select', 'from', 'where'] 
w = open('03_TextUpper.txt', 'w') 
 
with open('03_TextLower.txt', 'r') as file: 
 
    for line in file: 
        for word in line.split(): 
            if word in words: 
                w.write( word.upper() ) 
 
    w.write( line )  

这会打印出特定单词的大写字母,但不会删除小写单词。

有没有更好的 Python 编写方法?

请您参考如下方法:

我建议您分两个阶段执行此操作:

words = ['select', 'from', 'where'] 
 
with open('03_TextUpper.txt') as f_input: 
    text = f_input.read() 
 
with open('03_TextUpper.txt', 'w') as f_output: 
    for word in words: 
        text = text.replace(word, word.upper()) 
 
    f_output.write(text) 

首先将整个文件读入内存并进行必要的更改。接下来打开要写入的文件并将其写回。

它使用 Python 字符串 replace()用大写字母替换每个单词。它一次性对整个文件执行此操作,而无需拆分文件。


这可以通过使用正则表达式来识别单词边界来改进:

import re 
 
words = ['select', 'from', 'where'] 
uppercase = lambda x: x.group(1).upper() 
re_replace = re.compile(r'\b({})\b'.format('|'.join(words))) 
 
with open('03_TextUpper.txt') as f_input: 
    text = f_input.read() 
 
with open('03_TextUpper.txt', 'w') as f_output: 
    f_output.write(re_replace.sub(uppercase, text)) 

正则表达式能够在一次调用中执行所有替换。