在python中,使用正则表达式搜索字符串并用另一个替换它
我有一个db.sql文件,其中包含许多URL,如下所示在python中,使用正则表达式搜索字符串并用另一个替换它,python,csv,Python,Csv,我有一个db.sql文件,其中包含许多URL,如下所示 ....<td class=\"column-1\"><a href=\"http://geni.us/4Lk5\" rel=nofollow\"><img src=\"http://www.toprateten.com/wp-content/uploads/2016/08/25460A-Panini-Press-Gourmet-Sandwich-Maker.jpg \" alt=\"25460A Panini
....<td class=\"column-1\"><a href=\"http://geni.us/4Lk5\" rel=nofollow\"><img src=\"http://www.toprateten.com/wp-content/uploads/2016/08/25460A-Panini-Press-Gourmet-Sandwich-Maker.jpg \" alt=\"25460A Panini Press Gourmet Sandwich Maker\" height=\"100\" width=\"100\"></a></td><td class=\"column-2\"><a href=\"http://geni.us/4Lk5\" rel=\"nofollow\">25460A Panini Press Gourmet Sandwich Maker</a></td><td class....
4Lk5 8738 8/16/2016 0:20 https://www.amazon.com/gp/product/B00IWOJRSM/ref=as_li_qf_sp_asin_il_tl?ie=UTF8
Jx9Aj2 8738 8/22/2016 20:16 https://www.amazon.com/gp/product/B007EUSL5U/ref=as_li_qf_sp_asin_il_tl?ie=UTF8
9sl2 8738 8/22/2016 20:18 https://www.amazon.com/gp/product/B00C3GQGVG/ref=as_li_qf_sp_asin_il_tl?ie=UTF8
如您所见,有4LK5与Amazon产品URL相匹配
我已经阅读了csv文件,并使用python选择了唯一ID和Amazon产品url
def openFile(filename, mode):
index = 0
result = []
with open(filename, mode) as csvfile:
spamreader = csv.reader(csvfile, delimiter = ',', quotechar = '\n')
for row in spamreader:
result.append({
"genu_id": row[0],
"amazon_url": row[3]
});
return result
我必须添加一些代码,在db.sql中用genu_id搜索适当的URL,并替换为上面代码中描述的amazon_URL
请帮助我。如果您有这样一个预定义的结构,那么就不需要正则表达式-如果所有链接都是
http://geni.us/
您可以使用simplestr.replace()
读取CSV的每一行并替换SQL文件中的匹配项。比如:
import csv
with open("product.csv", "rb") as source, open("db.sql", "r+") as target: # open the files
sql_contents = target.read() # read the SQL file contents
reader = csv.reader(source, delimiter="\t") # build a CSV reader, tab as a delimiter
for row in reader: # read the CSV line by line
# replace any match of http://geni.us/<first_column> with third column's value
sql_contents = sql_contents.replace("http://geni.us/{}".format(row[0]), row[3])
target.seek(0) # seek back to the start of your SQL file
target.truncate() # truncate the rest
target.write(sql_contents) # write back the changed content
# ...
# Profit? :D
导入csv
以open(“product.csv”、“rb”)为源,open(“db.sql”、“r+”)为目标:#打开文件
sql_contents=target.read()#读取sql文件内容
reader=csv.reader(source,delimiter=“\t”)#构建一个csv读取器,选项卡作为分隔符
对于读卡器中的行:#逐行读取CSV
#替换任何匹配的http://geni.us/ 使用第三列的值
sql\u contents=sql\u contents.replace(“http://geni.us/{}.格式(第[0]行),第[3]行)
target.seek(0)#返回SQL文件的开头
target.truncate()#截断其余部分
target.write(sql#U内容)#写回更改的内容
# ...
#利润?:D
当然,如果原始CSV文件是逗号分隔的,请替换
CSV.reader()
调用中的分隔符-此处显示的分隔符似乎是制表符分隔的。为什么要使用正则表达式来进行此操作,而不是使用lxml.html
或类似的方法解析单元格内容?我对python不熟悉,所以我不太清楚。我想我必须使用正则表达式才能在…**-1\“>\”rel=nofol中选择“http://”+“geni.us/4Lk5”**