【发布时间】:2018-11-23 07:07:49
【问题描述】:
我有一个包含 1,000 个 URL 和公司名称的数据框,我需要将其转换为 HTML 链接并进行一些格式化。我写了一个函数,可以去列表和创建标签:
def linkcreate():
if row['url'] == '####' or row['url'] == '#####':
print('<span style="color: #293789!important; margin-bottom:0;">' + row['name'] + '</span>')
else:
print('<a href="' + row['url'] + '" target="_blank">' + row['name'] + '</a>')
if 语句 做了一些清理工作,因为有几十家公司没有网址。这些在df中表示为“####”和“#####”。对于这些,我添加了一个 span 标签 而不是 a 标签,并带有一些看起来像链接的样式。 else 语句只是根据 df 中的两列构造链接。
我想做的另一件事是将链接的一半放入,另一半放入 .下面是我的代码和解释:
# Calculates the middle point from the total count of rows in df
count = (int(data['url'].count()))/2
# Set counter to 0
counter = 0
for index, row in data.iterrows():
counter = counter + 1
# Before the first <a> tag start the first section <div>
if counter == 1:
print('<div class="side-1">')
# If counter is less then or equals to the half point of rows in df build the links using the linkcreate()
elif counter <= count:
linkcreate()
# If counter is +1 from the half way point of rows add the closing </div> and start the second <div>
elif counter == count + 1:
print('</div>')
print(' ')
print('<div class="side-2">')
# If counter is greater then the half point of rows in df build the rest of the links using the linkcreate()
elif counter > count:
linkcreate()
# Closing </div> tag for the second set of links.
print('</div>')
此代码有效,但它是最有效的方法吗?
【问题讨论】:
-
为什么要用print语句?
-
你看this的答案了吗?
-
@Ben.T 我是 Python 新手。我想用一个真实的场景来练习。认为打印是合适的。我应该改用什么?
-
@user32185 谢谢。我去看看。
-
@user3088202 好的,但最后你想创建一个文件以供以后使用,我假设还是不特别?
标签: python python-3.x pandas