【问题标题】:Python How to print the text read from a file without the escape char?Python如何打印从没有转义字符的文件中读取的文本?
【发布时间】:2016-12-12 19:47:57
【问题描述】:

python代码是这样的。我尝试从文件中读取数据。但是当我打印它时,我会得到square bracketescape char 的输出。如果我只是打印从数据文件中复制的内容。正常显示。 结果是这样的: [u'\n\n\xefhello']

如何解决这个问题。 这是结果窗口。我尝试删除square bracket,但它不起作用。我尝试通过utf-8 对字符串进行编码,但都不起作用。

而我从数据文件中读取的str类型是<type 'unicode'>

20161212185023.bmp

from bs4 import BeautifulSoup
import re

f = open('sgsres.txt', 'r')
content = f.read()
cleantext = BeautifulSoup(content, "lxml").text
cleantext = re.sub('[\[\]]', '', cleantext)
print cleantext

--- 更新--- @鲍里斯

我根据你的回答重写了代码,但我得到的输出是这样的。 每个字符输出在一行上,转义字符似乎仍然打印为原始文本。 20161212193059.bmp

---更新---

当我使用acsii 对字符串进行编码并忽略这样的错误时,此问题已得到解决。 text = text.encode('ascii',errors='ignore') 但我仍然不知道为什么。

【问题讨论】:

    标签: python string


    【解决方案1】:

    Square brackets 表示您正在使用list

    至于strings 里面的list,你可以这样做:

    from bs4 import BeautifulSoup
    import re
    
    f = open('sgsres.txt', 'r')
    content = f.read()
    cleantext = BeautifulSoup(content, "lxml").text
    for item in cleantext:
        item = item.strip()
        print item
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-16
      • 1970-01-01
      • 1970-01-01
      • 2012-10-25
      • 1970-01-01
      相关资源
      最近更新 更多