简体   繁体   English

从文件python读取时的不同文本

[英]Different text when reading from file python

I am using Python 2.7 我正在使用Python 2.7

The text I get from reading a file is different from the text I assign directly to a variable. 我从读取文件中获得的文本与我直接分配给变量的文本不同。

import unittest
class test_things(unittest.TestCase):
    def test_bad_read_stack_overflow(self):
        text_var = """[] Lorem Ipsum Lorem Ipsum Lorem Ipsum
Lorem Ipsum
Lorem Ipsum Lorem Ipsum Lorem Ipsum
*** Lorem Ipsum

Lorem Ipsum Lorem Ipsum Lorem Ipsum
Lorem Ipsum Lorem Ipsum
Lorem Ipsum Lorem Ipsum ** []

Lorem Ipsum
* Lorem IpsumLorem Ipsum
Lorem IpsumLorem IpsumLorem Ipsum
[] Lorem Ipsum
Lorem Ipsum
Lorem IpsumLorem Ipsum



        """

        import io
        text_file = io.open("unittest_data/example_for_stack_overflow", "r", encoding="utf-8").read()

        self.assertEqual(text_var, text_file)

The assertion fails. 断言失败。

In the file, "example_for_stack_overflow" I have this: 在文件"example_for_stack_overflow"我有这个:


[] Lorem Ipsum Lorem Ipsum Lorem Ipsum
Lorem Ipsum
Lorem Ipsum Lorem Ipsum Lorem Ipsum
*** Lorem Ipsum

Lorem Ipsum Lorem Ipsum Lorem Ipsum
Lorem Ipsum Lorem Ipsum
Lorem Ipsum Lorem Ipsum ** []

Lorem Ipsum
* Lorem IpsumLorem Ipsum
Lorem IpsumLorem IpsumLorem Ipsum
[] Lorem Ipsum
Lorem Ipsum
Lorem IpsumLorem Ipsum

For clarity, because here it doesn't appear, there are 4 \\n characters at the end. 为了清楚起见,因为这里没有出现,所以末尾有4个\\ n字符。

... IpsumLorem Ipsum\\n\\n\\n\\n ... IpsumLorem Ipsum \\ n \\ n \\ n \\ n

It's the exact same text I have assigned to text_var . 这与我分配给text_var文本text_var

Why is this problem occurring and how can I fix it? 为什么会出现此问题,我该如何解决?

Thanks! 谢谢!

Have you examined the error message in detail? 您是否详细检查了错误消息?

AssertionError: '[] L[279 chars]rem Ipsum\nLorem Ipsum\nLorem IpsumLorem Ipsum\n\n\n\n        ' != '[] L[279 chars]rem Ipsum\nLorem Ipsum\nLorem IpsumLorem Ipsum\n\n\n\n'

There are a couple of spaces at the end of the string ( '[...]\\n\\n ' ) that are not in the file ( '[...]\\n\\n' ). 字符串( '[...]\\n\\n ' )的末尾有几个空格,不在文件( '[...]\\n\\n' )中。

When you close the string the spaces in front of """ are included. This should work: 当您关闭字串时,会在"""前面加上空格,这应该可以运作:

    def test_bad_read_stack_overflow(self):
        text_var = """[] Lorem Ipsum Lorem Ipsum Lorem Ipsum
Lorem Ipsum
Lorem Ipsum Lorem Ipsum Lorem Ipsum
*** Lorem Ipsum

Lorem Ipsum Lorem Ipsum Lorem Ipsum
Lorem Ipsum Lorem Ipsum
Lorem Ipsum Lorem Ipsum ** []

Lorem Ipsum
* Lorem IpsumLorem Ipsum
Lorem IpsumLorem IpsumLorem Ipsum
[] Lorem Ipsum
Lorem Ipsum
Lorem IpsumLorem Ipsum



"""

(shrug) somewhere your file text is not the same as the variable text. (耸肩)文件文本与变量文本不同。

Make sure they are identical by 确保它们相同

with open("unittest_data/example_for_stack_overflow", "w") as outf:
    outf.write(text_var)

then run your code again and it should work. 然后再次运行您的代码,它应该可以工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM