目前,我使用Find All
(Cntrl+ F old_var
,alt+ enter new_var
)来实现这一点,但这会替换我的评论和字符串中的单词。
评论这个答案建议PyRefactor 插件这需要绳索。这些工具的默认值似乎对我的目的来说太过苛刻。我只想用 Sublime Text 3 重构独立 Python 脚本中的变量名。
因此在类似这样的脚本中
# Where did my hat go?
hat = 0
print(hat)
print("hat")
只需按一下热键,即可将变量hat
(不在字符串或注释中)替换为其他变量。无需特殊的项目文件夹/配置,并且多个文件中没有任何变化。不幸的是,Find All hat -> llama
确实如此...
# Where did my llama go?
llama = 0
print(llama)
print("llama")
编辑:
我很欣赏 @Toto 的正则表达式解决方案,但我还不太熟练,想要一种更一致、更容易记住的方法。是否有一个插件(或者我可以编写一个?)可以识别所有全局定义和声明的变量(函数调用中的参数等),并允许进行简单的查找和替换?
答案1
- Ctrl+H
- 寻找:
(?:^(?<!#).*\K|(<?!"))\bhat\b(?!")
- 代替:
llama
- 检查正则表达式
- 检查整个单词
- 检查包装
- Replace all
解释:
(?:
^ : beginning of line
(?<!#) : negative lookbehind, zero-length assertion that makes sure we don't have # before
.* : 0 or more any character
\k : forget all we have seen until this position
| : OR
(?<!") : negative lookbehind, zero-length assertion that makes sure we don't have " before
)
\b : word boundary to not match chat, remove it if you want to match chat also
hat : literally
\b : word boundary to not match hats, remove it if you want to match hats also
(?!") : negative lookahead, zero-length assertion that makes sure we don't have " after
鉴于:
# Where did my hat go?
hat = 0
chat = 0
print(hat)
print("hat")
print(chat)
给定示例的结果:
# Where did my hat go?
llama = 0
chat = 0
print(llama)
print("hat")
print(chat)
前: