2012-08-28 49 views
0

我需要刪除文本文檔中的以下標點符號和實體。從文本文檔中刪除標點符號和實體

  1. 刪除&#151&#148&#some number
  2. ; , . () [ ] * ! !
  3. &nbsp

我知道,我可以用它來刪除&#some number&nbsp。然而,作爲一個初學者,我不知道我是否可以做同樣的事情,刪除其他像;,

match = re.sub(r'&#146', '', open('test2.txt', 'r').read()) 

此外,有沒有我可以刪除它們中的任何方式一次而不是多次運行相同的代碼。

+0

相關:[從Python中的字符串中去除標點符號的最佳方式](http://stackoverflow.com/questions/265960/best-way-to-strip-punctuation-from-a-string-in- python) – jfs

回答

0

那些看起來像HTML和URL編碼的實體。

你可以使用各種手段

+0

謝謝。但是,有什麼方法可以刪除,*! 。立刻? – Jimmy

+0

're.sub(r「[] [* !.();]」,「」,your_string)''?或者,採取稍微不同的方法,嘗試匹配除了您想要的字符(如字母,數字和空格)之外的所有內容:'re.sub(r「[^ A-Za-z0-9]」,「」, your_string)'。 – Blckknght

0

如果你已經擁有了一切只是對其進行解碼在一個字符串中,你可以簡單地使用translate()

>>> s 
"hello there ! this is a string with $ some % characters I & don't (want!" 
>>> s.translate(None,"$!%&(") 
"hello there this is a string with some characters I don't want"