为了账号安全,请及时绑定邮箱和手机立即绑定

替换文本文件中的错误网址并在 Python 中修复它们

替换文本文件中的错误网址并在 Python 中修复它们

心有法竹 2023-06-27 16:28:00
我收到的 URL 已删除前向睫毛,我基本上需要更正文本文件内的 url。文件中的 URL 如下所示:https:www.ebay.co.ukitmReds-Challenge-184-214-Holo-Shiny-Rare-Pokemon-Card-SM-Unbroken-Bonds-Rare124315281970?hash=item1cf1c4aa32%3Ag%3AXBAAAOSwJGRfSGI1&LH_BIN=1我需要将其更正为:https://www.ebay.co.uk/itm/Reds-Challenge-184-214-Holo-Shiny-Rare-Pokemon-Card-SM-Unbroken-Bonds-Rare/124315281970?hash=item1cf1c4aa32%3Ag%3AXBAAAOSwJGRfSGI1&LH_BIN=1所以基本上我需要一个正则表达式或其他方式来编辑文件中每个 URL 的正斜杠,并替换文件中损坏的 URL。
查看完整描述

1 回答

?
江户川乱折腾

TA贡献1851条经验 获得超5个赞

while True:

    import time

    import re

    #input file

    fin = open("ebay2.csv", "rt")

    #output file to write the result to

    fout = open("out.txt", "wt")



    #for each line in the input file

    for line in fin:

        #read replace the string and write to output file

        fout.write(line.replace('https://www.ebay.co.uk/sch/', 'https://').replace('itm', '/itm/').replace('https:www.ebay','https://www.ebay'))


    with open('out.txt') as f:

      regex = r"\d{12}"

      subst = "/\\g<0>"

      for l in f:

          result = re.sub(regex, subst, l, 0, re.MULTILINE)

          if result:

              print(result)


    fin.close()

    fout.close()

    time.sleep(1)

我最终想出了这个。这有点笨拙,但完成工作的速度足够快。


查看完整回答
反对 回复 2023-06-27
  • 1 回答
  • 0 关注
  • 120 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信