2012-12-23 33 views
3

我试图将Powershell脚本转换为python脚本。我打算使用Shell脚本来简化grep和curl的使用,但我决定使用python来简化if语句。 这是我想要转换的PowerShell代码:将脚本从Powershell转换为Python-Regex未按预期工作

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 results 

重.search与此打印ReturnedRegExImageData.group(0)一起工作,但我想查找所有匹配,并且复制了foreach($ ReturnedRegExImageData中的$ Image)非常困难: 我尝试过为图像混淆在ReturnedRegExData和for循环从0到len(ReturnedRegExData),但它们不返回有效数据。我知道Python应该是简单的编码,但我处理它非常困难。

我已阅读.match,/ search和.findall类似的帖子,他们都在搜索部分,但没有任何结果如何获得有用的格式的结果。我已阅读了手册,但我也很难破译。

如何运行findall找到的结果,是否返回0,1个或更多结果。 0应该由if语句覆盖。

感谢您提供的任何帮助。

Ĵ

+0

什么是你的正则表达式?你的样本数据是什么?你目前得到什么输出? – 2012-12-23 16:05:08

+0

而且,你可以发布一些实际的Python代码吗? (Python在变量名称前面不使用'$')。 – kindall

回答

1

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) 
+0

这样做。我之前有一个用于处理ReturnedRegExImageData:Image中的Image,但由于某种原因,今天早上我的测试没有成功,但它现在正在工作。非常感谢你! – user1925193