Python:将文本文件中的特定单词大写
我试图编写一个python脚本来格式化SQL代码,以提高可读性 例如,将特定的小写单词转换为大写:选择->选择 我正试图使用Python中的读写函数来实现这一点。然而,我被卡住了。这是我的密码:Python:将文本文件中的特定单词大写,python,python-3.x,text,Python,Python 3.x,Text,我试图编写一个python脚本来格式化SQL代码,以提高可读性 例如,将特定的小写单词转换为大写:选择->选择 我正试图使用Python中的读写函数来实现这一点。然而,我被卡住了。这是我的密码: words = ['select', 'from', 'where'] w = open('03_TextUpper.txt', 'w') with open('03_TextLower.txt', 'r') as file: for line in file: for wo
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字符串将每个单词替换为大写字母。它可以一次完成整个文件,而无需拆分文件
这可以通过使用正则表达式来发现单词边界来改进:
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))
正则表达式能够在一次调用中执行所有替换。您可以在文件上迭代一次,然后将生成的列表写入输出文件:
words = ['select', 'from', 'where']
data = [i.strip('\n').split() for i in open('03_TextLower.txt')]
new_words = [[b for b in i if b.lower() in words] for i in data]
with open('03_TextUpper.txt', 'w') as f:
for line in new_words:
for word in line:
f.write("{}\n".format(word))
第三方库将执行以下操作:
>>> sql = 'select * from foo where id in (select id from bar);'
>>> print sqlparse.format(sql, reindent=True, keyword_case='upper')
SELECT *
FROM foo
WHERE id IN
(SELECT id
FROM bar);
这太棒了!但是,此代码将替换单词列表中的任何字符组合。例如,如果words=['select','from','where','in'],则带有'in'的单词(如获取)将成为获取。通常使用正则表达式来停止该操作。我已将其更新为使用一个。