2015-06-27 208 views
0

現在我的輸出到一個文件是這樣的:替換字符串的所有實例的字符串的Python

<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> 

我想刪除所有「A」和CSS標籤(< B>,</B>) 。我嘗試過使用卸下襬臂和.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 

上面的輸出是一個列表,這是我從一個webcrawling功能得到:

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) 

如何刪除所有標籤,以便只剩下日期?

+1

什麼是頁面編碼? –

回答

1

你已經有了一個有效的解決方案,但對於未來:

  1. 使用get_text()擺脫標籤

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

  • 使用.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'-')

    1

    我不確定,但我認爲aString.regex_replace('toFind','toReplace')應該可以工作。或者將它寫入文件,然後在其上運行sed:sed -i's/toFind/toReplace/g'

    +0

    謝謝,我只是使用Excel的查找和替換功能,只是試了一下,它的超級簡單。 – alphamonkey

    0

    如果你的Python 2源代碼有文字非ASCII字符,如Â那麼你應該爲錯誤消息指出聲明的源代碼編碼。把你的Python文件的頂部:

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

    確保文件被保存使用UTF-8編碼和使用Unicode字符串與文本的工作。

    +0

    如果你是一個比emacs更多的VIm用戶,你可以把它放在頂端:''#vim:set fileencoding = utf8:''。 – bufh

    +0

    @bufh:Python只要匹配['「coding [:=] \ s *([ - \ w。] +)」'正則表達式] [https://www.python.org/開發/ PEPS/PEP-0263 /)。 – jfs