[英]insert anchor tags using python in pandas dataframe
我在 pandas 數據框中的單獨列中有一個 url 列表和一個描述列表。 我試圖找出一種方法來使用 python 在描述的前幾個單詞中插入帶有鏈接的錨標記。
我有:
df.description[0]
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation"
df.link[0]
https://www.google.com
期望的輸出:
df.complete[0]
<a href="https://www.google.com"> Lorem ipsum dolor sit amet</a>, consectetur adipiscing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim
veniam, quis nostrud exercitation
描述列中的文本長度不同。 我試圖確保超鏈接以單詞的最后一個字符結束——錨標記中包含的單詞數量無關緊要。
您可以結合使用textwrap.shorten
和字符串操作。 嘗試這樣的事情:
from textwrap import shorten
# Change 20 to any value that makes sense
df["short_description"] = df["description"].apply(lambda s: shorten(s, width=20, placeholder=""))
df["description_link"] = (
# Create the start of the anchor tag
'<a href="' + df["link"] + '">'
# Add in the short description text
df["short_description"]
# Close the anchor tag
+ "</a>"
# Append the rest of the description
+ df["description"].str[df["short_description"].str.len:]
)
我的答案:
df["short_description"] = df["description"].apply(lambda s: shorten(s, width=20, placeholder=""))
df['remaining_desc'] = df.apply(lambda row : row['description'].replace(str(row['short_description']), ''), axis=1)
df['remaining_desc']
df["description_link"] = '<a href="' + df["story_link"] + '">' + df["short_description"] + "</a>" + df["remaining_desc"]
df['description_link']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.