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

查看:142
本文介绍了python2.7 - 怎么用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代码是第二次加工,就有乱码了。

解决方案

让我猜猜你干了什么:

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

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

解决方案: 滤掉这个文件

这篇关于python2.7 - 怎么用python处理.log文档里的隐藏乱码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆