2017-01-24 84 views
0

爲什麼它不刪除換行符? 頁數確定換行符未被刪除。爲什麼它不刪除換行符?

def save(self, *args, **kwargs): 
    self.full_text = re.sub('\n+', '', self.full_text) 
    self.pages_count = str(math.ceil(len(self.full_text.split(' '))/20)) 
    super(Book, self).save(*args, **kwargs) 
+1

? – furas

+1

或'self.full_text =''.join(self.full_text.split('\ n'))'。事實上,你的代碼適合我。 – DyZ

+0

@DYZ刪除但不保存 –

回答

0

你不能修改self.fulltext,re.sub是好的,如果你使用@property,你會得到一個錯誤。這裏是你所期望的,self.fulltext不會改變。

#!/usr/bin/env python 
    import unittest 
    import re 

    class Attribute(object): 
     def __init__(self): 
      self.fulltext = 'a\nb\nc\n\n1\n2\n' 

     def remove_newline(self, text): 
      txt_new = text 
      txt_new = re.sub('\n+', '', txt_new) 
      return txt_new 

     def remove_newline_class_attr(self): 
      self.fulltext = re.sub('\n+', '', self.fulltext) 
      return self.fulltext 

    class TestAttribute(unittest.TestCase): 

     def setUp(self): 
      attr = Attribute() 
      self.attr = attr 
      self.txt_wo_newline = 'abc12' 

     def test_remove_newline(self): 
      fulltext = self.attr.fulltext 
      txt = self.attr.remove_newline(fulltext) 
      self.assertEquals(txt, self.txt_wo_newline) 

     def test_property_no_change(self): 
      fulltext = self.attr.fulltext 
      txt = self.attr.remove_newline_class_attr() 
      self.assertEquals(txt, self.attr.fulltext) 

    if __name__ == '__main__': 
     suite = unittest.TestLoader().loadTestsFromTestCase(TestAttribute) 
     unittest.TextTestRunner(verbosity=2).run(suite) 
0

解決你能不能用'self.full_text = self.full_text.replace( '\ n', '')'的一個問題

def save(self, *args, **kwargs): 
    self.full_text = self.full_text.split('\r\n') 
    self.pages = str(math.ceil(len(self.full_text.split(' '))/20)) 
    super(Book, self).save(*args, **kwargs) 
相關問題