【问题标题】:Create hyperlink for each item in column in python(csv)为python(csv)中列中的每个项目创建超链接
【发布时间】:2021-08-13 05:19:39
【问题描述】:

我正在尝试为基于另一列的列中的每个项目创建超链接。

这里有一张图片可以帮助你更好地理解:

每个标题都应超链接到相应的 URL。 (当你点击apple时,它应该去apple.com,当你点击banana时它应该去banana.com,等等)有没有办法在python中对CSV文件执行此操作?

(假设我的数据是 2000 行)

提前致谢

【问题讨论】:

  • 你说你的最后一件事是有一个超链接,但一个人打开有一个超链接到底是什么?比如,我们是否有一个 Excel 文件或 Word 文档,他们点击它?我认为,作为最终产品的 CSV 不起作用,因为 CSV 中没有超链接。您可以从 CSV 开始,然后使用 Python 将其重新格式化/重新保存为 Excel 文件,其中 A 列是超链接。这就是你想要的吗?
  • 是的,我打算将其重新保存为 excel 文件。谢谢

标签: python csv hyperlink


【解决方案1】:

您可以使用(我使用)pandas 库从 csv 读取数据,然后将其写入 excel,并利用 Excel 函数HYPERLINK 使单元格成为超链接。 HYPERLINK 的 Excel 函数需要我们要访问的 url(以 http:// 或 https:// 开头),然后是可见文本或友好名称。

当您打开 Excel 文件时,它不会有一个带有蓝色下划线的超链接单元格文本。如果需要,您可以在一定程度上利用此解决方案并使用 XlsxWriter 模块。

import pandas as pd

df = pd.read_csv("path\test.csv") #put your actual path here
# this will read the file and save it is a 'dataframe', basically a table.
df['title'] = '=HYPERLINK("https://' + df["url"] +'","' + df["title"]+'")' 
"""the df that we originally pulled in has the columns 'title' and 'url'. This line re-writes the values in 
'title' to use the HYPERLINK formula in Excel, where the link is the value from the URL column with 'https://'
added to the beginning, and then uses the value from 'title' as the text the user will see in Excel"""
df.to_excel("save_location\test2.xlsx",index=False) #this saves the new file as an Excel. index=False removes the index column that was created when you first make any dataframe

如果你希望你的输出只是一列,他们点击的那一列,你的最后一行会略有不同: df['title'].to_excel("save_location\test2.xlsx",index=False)

【讨论】:

    【解决方案2】:

    没有用,或者你可能包含了太多的 's

    import pandas as pd
    df = pd.read_csv('test.csv')
    df['URL'] = 'https://url/'+df['id'].astype(str)
    keep_col = ['URL']
    newurl = df[keep_col]
    newurl.to_csv("newurl.csv", index=False)
    

    此代码正在运行,但输出文件未显示可点击的 url

    【讨论】:

    • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
    猜你喜欢
    • 2018-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-07
    • 2014-02-28
    • 1970-01-01
    • 2016-10-15
    • 2011-06-19
    相关资源
    最近更新 更多