![](/img/trans.png)
[英]Find and replace variable value in a .py file using another python program
[英]Looking to a build a simple find and replace program for file paths using Python
我认为我应该从说我是Python的新手开始。 我已经上了几课,对基础知识有了相当扎实的理解,但是我的技能仍然很有限,而且我自己获得的结果可能非常粗糙。 我目前正在尝试组合一个可以输出已编辑路径的查找和替换程序。 见下文:
filepaths = [
"\wwwtest\test\site\services\cogs\index.html",
"\wwwtest\test\site\dba\index.html"
]
find = "\wwwtest\test\site"
replace_one = "http:\\www.test.com"
replace_two = "https:\\www.test.com"
for paths in filepaths:
print(paths.replace(find, replace_one))
print(paths.replace(find, replace_two))
因此,从本质上讲,我想做的是输入文件路径和输出URL。 在shell中运行上述代码会产生以下结果:
http:\www.test.com\services\cogs\index.html
https:\www.test.com\services\cogs\index.html
http:\www.test.com\dba\index.html
https:\www.test.com\dba\index.html
我认为我或多或少都在正确的轨道上,但是输出显然存在一些问题,即删除每个URL的www前面的第二个\\。 我想这是Python将double \\解释为某种特殊字符的结果,但是我一直无法确定如何最好地解决此问题。
成功替换路径/ URL的第一个块之后,我还需要将每个\\替换为/(或者应该先出现?),这会产生自己的一系列问题。 到目前为止,以下代码是我尝试过的:
urls = [
"http:\www.test.com\services\cogs\index.html",
"https:\www.test.com\services\cogs\index.html"
]
find = '\'
replace = '/'
for paths in urls:
print(paths.replace(find, replace))
此代码产生以下内容:
SyntaxError: EOL while scanning string literal
我相信我缺少一些有关在Python中使用斜杠的信息。 非常感谢您提供有关如何最好地开发此类程序以及如何使代码高效的任何建议。 我还意识到,硬编码要操作到程序中的路径可能不是执行此操作的最有效方法,但是我可能将其留给一个单独的问题,以防止发布的内容超过已经存在的时间(尽管对于如何正确读取和写入此示例的文本文件的建议,也将不胜感激)。
谢谢你D
在python中, \\
是转义字符,因此,如果要字面表示\\
,则必须重复两次,即"C:\\\\Windows\\\\path"
或通过在r
之前加一个r
将其定义为字符串文字。字符串, r"C:\\Windows\\path"
这里有一些很好的例子,向您展示它是如何工作的。
\\
是转义序列的开始。
在第一部分中,如果您希望输出两个"\\\\"
,则需要这样编写:
replace_one = "http:\\\\www.test.com"
replace_two = "https:\\\\www.test.com"
如果希望找到\\
,则需要执行以下操作以转义转义序列:
find = '\\'
每次要使用\\
,请改用\\\\
。 因此,如果需要\\\\
,请使用\\\\\\\\
:
filepaths = [
"\\wwwtest\\test\\site\\services\\cogs\\index.html",
"\\wwwtest\\test\\site\\dba\\index.html"
]
find = "\\wwwtest\\test\\site"
replace_one = "http:\\\\www.test.com"
replace_two = "https:\\\\www.test.com"
for paths in filepaths:
print(paths.replace(find, replace_one))
print(paths.replace(find, replace_two))
和
urls = [
"http:\\\\www.test.com\\services\\cogs\\index.html",
"https:\\\\www.test.com\\services\\cogs\\index.html"
]
find = '\\'
replace = '/'
for paths in urls:
print(paths.replace(find, replace))
应该解决您的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.