【问题标题】:How to clean \xc2\xa0 \xc2\xa0..... in text data如何清理文本数据中的\xc2\xa0 \xc2\xa0.....
【发布时间】:2018-02-03 23:14:19
【问题描述】:

当我尝试使用以下 python 代码读取文本文件时:

     with open(file, 'r') as myfile:
          data = myfile.read()

有一些奇怪的字符以 \x.... 开头,它们代表什么以及如何在读取文本文件时摆脱它们?

例如

...... \xc2\xa0 \xc2\xa0 第 1 章 1984 年星期二 \xe2\x80\x9chey ,杰克,你妈妈派我来接你 \xe2\x80\x9d 雅各布·罗宾斯比接受陌生人搭车,但当他妈妈\xe2\x80\x99的朋友ronny在学校门口等他时,他很不情愿地上了车\xe2\x80\x9cm我的名字叫jacob.......

【问题讨论】:

  • 这是python 2还是python 3?
  • 希望雅各布没事

标签: python python-2.7 python-3.x


【解决方案1】:

下面的代码解决了这个问题

path.decode('utf-8','ignore').strip()

【讨论】:

    【解决方案2】:
     def main():
          args = parse_args()
          if args.file :
              //To clean \xc2\xa0 \xc2\xa0… in text data 
              file_to_read = args.file.decode('utf-8','ignore').strip() 
              f = open(file_to_read, "r+")
              text_from_file = f.read()  
          else :
              text_from_file = sys.argv[1]
    

    【讨论】:

      【解决方案3】:

      那些是字符串转义。它们用十六进制值表示一个字符。例如,\x240x24,这是美元符号。

      >>> '\x24'
      '$'
      >>> chr(0x24)
      '$'
      

      一个这样的转义(从你提供的那些)是\xc2,即Â,一个带抑扬符的大写字母A。

      【讨论】:

        【解决方案4】:

        这是 UTF-8 编码的文本。您以 UTF-8 格式打开文件。

        with open(file, 'r', encoding='utf-8') as myfile:
           ...
        

        2.x:

        with codecs.open(file, 'r', encoding='utf-8') as myfile:
           ...
        

        Unicode In Python, Completely Demystified

        【讨论】:

        • io.open(file, 'r', encoding='utf-8') 将在 2 和 3 中工作(除非他们使用 2.5 或更早版本,在这种情况下他们有更大的问题)。
        • 好吧,如果我运行你的代码,我得到:u"\xa0\n \n \nNo Front Brothers \n \n \nA BoonieRats - Jake Olson Novel \n \n \nby Bill Ellingsen \ n \n\n \n\xa0\n \n \nNo Front Brothers by Bill Ellingsen \n \n版权所有\xa9 2011 by Bill Ellingsen\n \n \n由Bill Ellingsen 出版\n \n保留所有权利\n \n \ n封面设计由 Daniel Cosgrove \n \n版权所有 \xa9 2011 by Bill Ellingsen\n \n \n
        猜你喜欢
        • 2021-04-18
        • 2015-12-01
        • 2016-02-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-04-16
        相关资源
        最近更新 更多