目标是读取html文件并将MyWord的所有实例更改为MyWord;但是,如果在路径、文件名或脚本中或作为路径、文件名或脚本的一部分,则不得更改该单词:
href="..."
src="..."
url(...)
class="..."
id="..."
script inline or linked (file name) --> <script ...></script>
styles inline or linked (file name) --> <link ...> <style></style>
现在是所有问题中的一个问题:如何确定单词的实例是否处于可以更改的位置?(或者,您如何确定该单词是否在上面列出的某个位置内并且不应更改?)你知道吗
这是我的代码,它可以更改为逐行读取等,但我只是不能想到如何定义和执行一个规则,以匹配上述。。。你知道吗
在这里:
#!/usr/bin/python
import os
import time
from stat import *
def fileExtension(s):
i = s.rfind('.')
if i == -1:
return ''
tmp = '|' + s[i+1:] + '|'
return tmp
def changeFiles():
# get all files in current directory with desired extension
files = [f for f in os.listdir('.') if extStr.find(fileExtension(f)) != -1]
for f in files:
if os.path.isdir(f):
continue
st = os.stat(f)
atime = st[ST_ATIME] # org access time
mtime = st[ST_MTIME] # org modification time
fw = open(f, 'r+')
tmp = fw.read().replace(oldStr, newStr)
fw.seek(0)
fw.write(tmp)
fw.close()
# put file timestamp back to org timestamp
os.utime(f,(atime,mtime))
# if we want to check subdirectories
if checkSubDirs :
dirs = [d for d in os.listdir('.') if os.path.isdir(d)]
for d in dirs :
os.chdir(d)
changeFiles()
os.chdir('..')
# ==============================================================================
# ==================================== MAIN ====================================
oldStr = 'MyWord'
newStr = 'Myword'
extStr = '|html|htm|'
checkSubDirs = True
changeFiles()
有人知道怎么做吗?有什么建议吗?任何帮助都是感激的,打了我的大脑两天了,只是想不出什么。你知道吗
lxml有助于完成这类任务。你知道吗
上面打印的是:
注意:如果还需要对脚本标记的内容进行特殊处理,则需要使上述代码稍微复杂一些,例如
使用regex这里有一个示例,您可以从中开始,希望这对您有所帮助:
参考号:http://docs.python.org/library/re.html
相关问题 更多 >
编程相关推荐