python - 删除 pandas 中的 html 标签

标签 python html python-3.x regex pandas

我在 Python 3.5.1 上使用 pandas 库。如何从字段值中删除 html 标签?这是我的输入和输出:

enter image description here

我的代码返回错误:

import pandas as pd

code=[1,2,3]
overview =['<p>Environments subject.</p>',
          '<ul><li> property ;</li></ul><ul><li>markets and exchange;</li></ul>',
          '<p class="MsoNormal" style="margin: 0cm 0cm 0pt;">']
# '<p class="SSPBodyText" style="padding: 0cm; text-align: justify;">The subject.</p>']
df= pd.DataFrame(overview,code)

df.columns = ['overview']
df['overview_copy'] = df['overview']

# print(df)

tags_list = ['<p>' ,'</p>' , '<p*>',
             '<ul>','</ul>',
             '<li>','</li>',
             '<br>',
             '<strong>','</strong>',
             '<span*>','</span>',
             '<a href*>','</a>',
             '<em>','</em>']

for tag in tags_list:
#     df['overview_copy'] = df['overview_copy'].str.replace(tag, '')
  df['overview_copy'].replace(to_replace=tag, value='', regex=True, inplace=True)
print(df)

最佳答案

Pandas 的方式是使用 Series.str.replace :

df['overview_copy'] = df['overview_copy'].str.replace(r'<[^<>]*>', '', regex=True)

详细信息:

  • < - 一个<字符
  • [^<>]* - 零个或多个字符 <>尽可能多
  • > - 一个>字符。

请参阅regex demo .

Pandas 输出:

>>> df['overview_copy']
1               Environments subject.
2     property ;markets and exchange;
3                                    
Name: overview_copy, dtype: object
>>> 

关于python - 删除 pandas 中的 html 标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45999415/

相关文章:

php - PIE.htc 位置 - 我怎么知道 html 的相对路径在哪里 - zencart

python - scipy.stats.linregress 中假设检验的类型

python - np.mean 的 Numba 失败

python - 如何删除使用 tempfile.mkdtemp 创建的目录?

python - 密码生成器的字符顺序如何随机化

javascript - 通过ajax将上传的excel文件数据传递给python

jquery - Jquery Nivo Slider 转换如何工作?

javascript - 将乘法金额结果限制为小数点后 2 位

Python - 解构函数不删除对象实例

python - 简化此 python 代码