怎么用python处理.log文档里的隐藏乱码?

下面这段代码是用来把一个个单词提取出来然后转化成ID

def indexFile(pt, res_pt):
print 'index file: ', pt
wf = open(res_pt, 'w')
for l in open(pt):
    ws = l.strip().split()
    for w in ws:
        if not w2id.has_key(w):
            w2id[w] = [len(w2id), 1]
        else:
            w2id[w][1] += 1

    wids = [w2id[w][0] for w in ws]        
    print >>wf, ' '.join(map(str, wids))

print 'write file: ', res_pt

但是提取出来的结果在.txt文件里看是这样的:

图片描述

把上面这段乱码复制到sublime却变成了这样:

图片描述

把它复制到segmentfault的editor却变成了这样:

图片描述

原本的文件看不到这些乱码,而这些内容是从.log 文档里提取出来的。请问各位大大,有什么方法可以解决这个问题吗? 谢谢!

这是原本的.log文件节选:

[05:54:07] [Server thread/INFO]: [0;34;1mAutoSaving[m
[05:54:07] [Server thread/INFO]: [0;34;1mAutoSave Complete[m
[05:54:12] [Server thread/INFO]: [AutoSaveWorld] Loading AutoSaveWorld v4.14.1
[05:54:12] [Server thread/INFO]: [NoCheatPlus] Loading NoCheatPlus v3.12.0-SNAPSHOT-sMD5NET-b793
[05:54:12] [Server thread/INFO]: [NoCheatPlus] onLoad: Early set up of static API, configuration, logging.
[05:54:12] [Server thread/INFO]: [NoCheatPlus] Logging system initialized.

无论用txt editor 或是sublime打开都看不到乱码。

然后我用python处理了一遍, 变成这样的文件:

can we please use redstone
hey admin
admincan you come
hey admin
hi
Helllo It's Stampy
come to my plot
...

也看不到乱码。

一开始的python代码是第二次加工,就有乱码了。

阅读 3.5k
1 个回答

让我猜猜你干了什么:

搜索一个目录下的所有文件,对它们作分析

然而mac中系统会自动生成一个叫 .DS_Store的隐藏文件,里面是二进制数据。因此不幸也被你拿来处理了。

解决方案: 滤掉这个文件

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题