我正在尝试将Powershell脚本转换为python脚本。我打算使用Shell脚本来简化grep和curl的使用,但我决定使用python来简化if语句。这是我试图转换的Powershell代码:
Powershell代码(效果很好):
$ReturnedRegExData = SearchStringAll -StringToSearch $Data -RegEx $ImgURLRegex
if ($ReturnedRegExData) #Check Existance of Matches
{
foreach ($Image in $ReturnedRegExImageData) #Run Through all Matches
#Can then get the result from the group of results and run through them 1 at a time via $Image
}
else
{
#exit
}这是我在Python中的尝试,效果不是很好
ReturnedRegExData = re.findall($ImgURLRegex , $Data)
if ReturnedRegExImageData: #Check existance of Matches (Works)
print "found"
else:
sys.stderr.write("Error finding Regex \r\n")
return
$For Loop running through resultsre.search使用了这个print ReturnedRegExImageData.group(0),但我希望找到所有匹配项,并且很难复制foreach ($ReturnedRegExImageData中的$Image)这行代码:我尝试过在ReturnedRegExData中修改for Image和从0到len(ReturnedRegExData)的for循环,但它们都不返回有效数据。我知道Python应该是简单的编码,但我在处理它时遇到了非常困难的事情。
我读过类似的关于.match,/search和.findall的帖子,它们都讨论了搜索部分,但没有讨论如何以有用的格式获得结果。我已经看过手册了,但我也很难破译它。
如何遍历findall找到的结果,无论是返回0、1还是更多结果。0应该包含在if语句中。
感谢您能提供的任何帮助。
J
发布于 2012-12-24 00:12:05
findall函数返回一个字符串列表。所以你可以这样做:
found = re.findall(img_url_regex, data)
if not found: # the list is empty
sys.stderr.write("Error finding Regex \r\n")
else:
for imgurl in found:
print 'Found image:', imgurl
# whatever else you want to do with the URL.请注意,使用$开始变量名不是有效的python;
In [3]: $foo = 12
File "<ipython-input-3-38be62380e9f>", line 1
$foo = 12
^
SyntaxError: invalid syntax如果您想替换部分已找到的URL,可以使用sub()方法。它使用MatchObject。下面是我自己的脚本中的一个示例。我用它来把<img alt='pic' class="align-left" src="static/test.jpg" />改成<img alt='pic' class="align-left" src="static/images/test.jpg" />
with open(filename, 'r') as f:
data = f.read()
# fix image links
img = re.compile(r'src="[\./]*static/([^"]*)"')
data = img.sub(lambda m: (r'src="' + prefix + 'static/images/' +
m.group(1) + r'"'), data)
with open(filename, 'w+') as of:
of.write(data)https://stackoverflow.com/questions/14012378
复制相似问题