我试图以某种方式将regex中的多个匹配写入单行文件。
matches = re.findall(<form>(.*?)</form>, line, re.DOTALL)
for form in matches:
form = ("'" + form + "', ")
f = open(new_file, 'a+')
f.write(form.rstrip('\n'), )
上面给了我这个:
'form1', 'form2',....,'formN',
如何将它们括在括号中,最后没有逗号,如下所示?
('form1', 'form2',....,'formN')
非常感谢。
答案 0 :(得分:1)
这样的东西?
matches = re.findall(<form>(.*?)</form>, line, re.DOTALL)
if matches:
f = open(new_file, 'a+')
f.write("('%s')" % "', '".join(matches))
f.close()
答案 1 :(得分:0)
根据official documentation,re.findall
返回“字符串中所有非重叠匹配的匹配项,字符串列表”。
因此,
myline = "("
n = len( matches )
if ( n > 0 ) :
myline = myline + "'" + matches[ 0 ] + "'"
for i in range( 1, n ) :
myline = myline + ", '" + matches[ i ] + "'"
myline = myline + ")"
# WRITE TO FILE
答案 2 :(得分:0)
我是python的新手,只是陷入问题,我有脚本可以使用单一正则表达式解析html行。我想使用多个单词进行解析,以便获得更合适的结果。我的代码附在下面
#!/usr/bin/python
#!/usr/bin/env python
# Python file to monitor pastebin for pastes containing the passed regex
import sys
import time
import urllib
import re
f = open('sj1.txt', 'w')
# User-defined variables
time_between = 7 #Seconds between iterations (not including time used to fetch pages - setting below 5s may cause a pastebin IP block, too high may miss pastes)
error_on_cl_args = "Please provide a single regex search via the command line" #Error to display if improper command line arguments are provided
# Check for command line argument (a single regex)
if len(sys.argv) != 3:
search_term = sys.argv[1] and
sys.argv[2] and
sys.argv[3]
print search_term
else:
print error_on_cl_args
exit()
iterater = 1
while(iterater):
counter = 0
print "Scanning pastebin - iteration " + str(iterater) + "..."
#Open the recently posted pastes page
try:
url = urllib.urlopen("http://pastebin.com/archive")
html = url.read()
url.close()
html_lines = html.split('\n')
for line in html_lines:
if counter < 308:
#print line
if re.search(r'<td><img src="/i/t.gif" class="i_p0" alt="" /><a href="/[0-9a-zA-Z]{8}">.*</a></td>', line ):
#print 'I am here'
link_id = line[61:69]
print link_id
#Begin loading of raw paste text
url_2 = urllib.urlopen("http://pastebin.com/raw.php?i=" + link_id)
raw_text = url_2.read()
#print raw_text
url_2.close()
#if search_term in raw_text:
if re.search(r''+search_term, raw_text):
print >> f, "FOUND " + search_term + " in http://pastebin.com/raw.php?i=" + link_id
counter += 1
except(IOError):
print "Network error - are `enter code here`you connected?"
except:
print "Fatal error! Exiting."
exit()
iterater =0
time.sleep(time_between)