通过 Python 链接到 csv 文件中的超链接

如何使 CSV 文件中的所有链接都指向超链接?- 只需将 HTML 标签添加到所有带有链接的字段


我认为可以通过 Python


CSV 字符串看起来像


"Name","CompanyName","Value1","Value2","Value3","Value4","Value5","Value6","Value7","Url","Value8 ""Value8.1"""

"Name","Company1","SomeValue1","SomeValue2","SomeValue3","SomeValue4","SomeValue5","SomeValue6","SomeValue7","https://company1.com","Some"Value8 ""Value8.1"""

"Name","Company2","SomeValue1","SomeValue2","SomeValue3","SomeValue4","SomeValue5","SomeValue6","SomeValue7","https://company2.com","Some"Value8 ""Value8.1"""

应该看起来像:


"Name","CompanyName","Value1","Value2","Value3","Value4","Value5","Value6", "Value7","Url","Value8"

"Name","Company1","SomeValue1","SomeValue2","SomeValue3","SomeValue4","SomeValue5","SomeValue6","SomeValue7","<a href="https://company1.com">https://company1.com</a>","Some"Value8 ""Value8.1"""

"Name","Company2","SomeValue1","SomeValue2","SomeValue3","SomeValue4","SomeValue5","SomeValue6","SomeValue7","<a href="https://company2.com">https://company2.com</a>","Some"Value8 ""Value8.1"""

"Name","Company3","SomeValue1","SomeValue2","SomeValue3","SomeValue4","SomeValue5","SomeValue6","SomeValue7","<a href="https://company3.com">https://company3.com</a>","Some"Value8 ""Value8.1"""

我尝试了 awk 和 sed,但是当我在文件中指定一列时会出错。我觉得脚本应该找到所有链接并将其插入 HTML 标签。但我还不明白它是如何工作的


牧羊人nacy
浏览 323回答 1
1回答

不负相思意

这是一个快速而肮脏的例子,说明如何做到这一点。您可以在此处查看 csv 模块的示例您的示例数据有一些额外的空格 - 如果您的真实数据是这样的,您可以使用该strip()方法删除空格。如果您的 URL 在同一列中不一致,那么这将不起作用,您将需要使用 regex 或 urllib 来识别它们。import csvcount = 0with open('test.csv', 'r') as f:&nbsp; &nbsp; csv_reader = csv.reader(f)&nbsp; &nbsp; with open('outfile.csv', 'w') as outfile:&nbsp; &nbsp; for row in csv_reader:&nbsp; &nbsp; &nbsp; &nbsp; row[0] = f'"{row[0]}'&nbsp; &nbsp; &nbsp; &nbsp; if count < 1:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; outfile.write('","'.join(row) + '"\n')&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; count += 1&nbsp; &nbsp; &nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; row[-2] = f'<a href="{row[-2]}">{row[-2]}</a>'&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; outfile.write('","'.join(row) + '"\n')
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python