【问题标题】:Replacing all instances of string in string Python替换字符串Python中的所有字符串实例
【发布时间】:2015-06-27 21:38:01
【问题描述】:

现在我的文件输出如下:

<b>Nov 22–24</b>   <b>Nov 29–Dec 1</b>    <b>Dec 6–8</b> <b>Dec 13–15</b>   <b>Dec 20–22</b>   <b>Dec 27–29</b>   <b>Jan 3–5</b> <b>Jan 10–12</b>   <b>Jan 17–19</b>   <b><i>Jan 17–20</i></b>    <b>Jan 24–26</b>   <b>Jan 31–Feb 2</b>    <b>Feb 7–9</b> <b>Feb 14–16</b>   <b><i>Feb 14–17</i></b>    <b>Feb 21–23</b>   <b>Feb 28–Mar 2</b>    <b>Mar 7–9</b> <b>Mar 14–16</b>   <b>Mar 21–23</b>   <b>Mar 28–30</b>   

我想删除所有的“”和css标签()。我尝试使用 .remove 和 .replace 函数,但出现错误:

SyntaxError: Non-ASCII character '\xc2' in file -- FILE NAME-- on line 70, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details

上面的输出在一个列表中,我从一个网络爬虫函数中得到:

def getWeekend(item_url):
    dates = []
    href = item_url[:37]+"page=weekend&" + item_url[37:]
    response = requests.get(href)
    soup = BeautifulSoup(response.content, "lxml")  # or BeautifulSoup(response.content, "html5lib")
    date= soup.select('table.chart-wide > tr > td > nobr > font > a > b')
    return date

我把它写到这样的文件中:

for item in listOfDate:
    wr.writerow(item)

如何删除所有标签,只留下日期?

【问题讨论】:

  • 页面编码是什么?

标签: python beautifulsoup web-crawler


【解决方案1】:

我不确定,但我认为 aString.regex_replace('toFind', 'toReplace') 应该可以工作。要么将其写入文件,然后在其上运行 sed,例如: sed -i 's/toFind/toReplace/g'

【讨论】:

  • 谢谢,我就用excel的查找替换功能,试了一下,超级简单。
【解决方案2】:

您已经有了一个可行的解决方案,但对于未来:

  1. 使用get_text() 去除标签

date = soup.select('table.chart-wide &gt; tr &gt; td &gt; nobr &gt; font &gt; a &gt; b').get_text()

  1. 使用.replace(u'\xc2',u'') 删除Âu 使 u'\xc2' 成为一个 unicode 字符串。 (这可能需要一些编码,但对我来说 get_Text() 已经返回一个 unicode 对象。)

(另外,可能考虑.replace(u'\u2013',u'-'),因为现在,你有一个破折号:P。)

date = date.replace(u'\xc2',u'').replace(u'\u2013',u'-')

【讨论】:

    【解决方案3】:

    问题是您没有来自网站的 ASCII 字符串。在操作之前,您需要将非 ASCII 文本转换为 Python 可以理解的内容。

    如果有机会,Python 将使用 Unicode。如果你只是看看,那里有很多信息。例如,您可以从本网站的其他问题中找到更多帮助:

    Python: Converting from ISO-8859-1/latin1 to UTF-8

    python: unicode in Windows terminal, encoding used?

    What is the difference between encode/decode?

    【讨论】:

      【解决方案4】:

      如果您的 Python 2 源代码包含文字非 ASCII 字符,例如 Â,那么您应该按照错误消息的说明声明源代码编码。放在 Python 文件的顶部:

      # -*- coding: utf-8 -*-
      

      确保使用 utf-8 编码保存文件并使用 Unicode 字符串处理文本。

      【讨论】:

      猜你喜欢
      • 2014-03-14
      • 2021-08-16
      • 1970-01-01
      • 2011-09-29
      • 2017-09-04
      • 2012-11-14
      • 1970-01-01
      • 1970-01-01
      • 2018-07-05
      相关资源
      最近更新 更多