我想用 BeautifulSoup 中的锚链接包装一些尚未链接的单词。我用它来实现它:
from bs4 import BeautifulSoup
import re
text = ''' replace this string '''
soup = BeautifulSoup(text)
pattern = 'replace'
for txt in soup.findAll(text=True):
if re.search(pattern,txt,re.I) and txt.parent.name != 'a':
newtext = re.sub(r'(%s)' % pattern,
r'<a href="#\1">\1</a>',
txt)
txt.replaceWith(newtext)
print(soup)
Run Code Online (Sandbox Code Playgroud)
不幸返回
<html><body><p><a href="#replace">replace</a> this string </p></body></html>
Run Code Online (Sandbox Code Playgroud)
而我正在寻找:
<html><body><p><a href="#replace">replace</a> this string </p></body></html>
Run Code Online (Sandbox Code Playgroud)
有没有办法告诉 BeautifulSoup 不要逃避链接元素?
要替换的简单正则表达式在这里不起作用,因为我最终不仅要替换一个模式,而且要替换多个模式。这就是为什么我决定使用 BeautifulSoup 来排除已经是链接的所有内容。
使用divhtml和css 创建全屏时,有两个主要选项:
使用方法: html, body, #myDiv {height: 100%, width: 100%}
要么: #myDiv{position: absolute; top:0px; bottom:0px; width: 100%}
一个相对于另一个有什么优势,或者它们可以互换使用吗?
我有一个带有datetimeindex的pandas DataFrame。我想创建一个label由数据的年份和月份组成的列。
我发现要做的方法是制作该列的副本并对其进行操作(我必须这样做,因为a DateTimeIndex没有apply方法)。我敢肯定,虽然有一定一种方法可以直接对索引进行操作,但是我找不到它:
import pandas as pd
import numpy as np
df = pd.DataFrame(index=pd.date_range(start="2012-01-01", end="2013-01-01", freq='D'), data=range(367))
monthly = df.resample("M")
monthly["label"] = monthly.index
monthly["label"] = monthly["label"].apply(lambda x: x.strftime("%Y-%m"))
Run Code Online (Sandbox Code Playgroud)
哪里monthly.head()给我:
0 label
2012-01-31 15.0 2012-01
2012-02-29 45.0 2012-02
2012-03-31 75.0 2012-03
2012-04-30 105.5 2012-04
2012-05-31 136.0 2012-05
Run Code Online (Sandbox Code Playgroud)
正是我想要的,我只想在源代码中没有倒数第二行的情况下执行此操作,因此我将其用作解决方法。