为什么它不删除换行符?

时间:2017-01-24 00:54:25

标签: python regex django python-3.x django-models

为什么它不会删除换行符? 确定换行符的页数不会被删除。

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)

2 个答案:

答案 0 :(得分: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)

答案 1 :(得分:0)

解决了问题

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)