2012-12-23 38 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