簡體   English   中英

在python中,使用正則表達式搜索字符串並將其替換為另一個

[英]In python, search strings using regular expression and replace it with another

我有一個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 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....

如您所見,文件中有http://geni.us/4Lk5 \\。

我還有另一個product.csv文件,其中包含ID(例如上述4LK5 )和Amazon產品URL,如下所示。

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/<geni_id>的形式,則可以通過讀取http://geni.us/<geni_id> str.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文件以逗號分隔,請在csv.reader()調用中替換分隔符-您在此處顯示的分隔符似乎用制表符分隔。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM