linux轉碼命令列和python兩種實現,linuxpython

來源:互聯網
上載者:User

linux轉碼命令列和python兩種實現,linuxpython

今天從windows拷到linux的檔案出現亂碼,其實直接通過file, iconv命令轉碼就行了

/*如果是命令列來實現的話,也是可以的,而且從某種程度上來說是可能更加便捷的*/
file genghao.cpp /*根據這個可以知道這個檔案的大概編碼類別型*/
iconv -l
/*看看我們的iconv工具是否支援這種編碼,不過不支援,選擇一個比較接近的就行*/
iconv -f  XXXX
(原始編碼) -t YYY(你想要的編碼) genghao.cpp(原始檔案)  genhao.cpp(目標檔案)

如果希望多瞭解下上面幾個指令,可以參考博文:http://blog.csdn.net/echoisland/article/details/6660619, 裡面同時有提到file工具可能出現誤判的情況。

作為一個不安分的人,一個小的功能可以通過不同的工具來實現,用指令碼來實現轉碼也是很方便的
什麼語言呢?其實php, python , shell ... , 甚至跟進階的C++,C都可以用相應的檔案操作和一些介面來實現

閑的蛋疼就想用python實現轉碼

import chardet

fp = open('genhao.cpp', 'r+')

/*readlines讀取檔案,以行為單位的一個list*/
content ='\n'.join(fp.readlines())
print content
/*檔案指標回到檔案開頭*/
fp.seek(0)

/*read讀取整個檔案*/
content = fp.read()
print content
fp.seek(0)

/*readline讀取1行*/
tmp = fp.readline()
while tmp:
    content += tmp
    tmp = fp.readline()
print content

/*判斷檔案的編碼*/
charinfo = chardet.detect(content)
encoding = charinfo['encoding']
/*轉成utf-8*/
content = content.decode(encoding).encode('utf-8')
print content

搞定,等有時間吧其他工具的實現也寫寫。

按照慣例, 水一句:語言,只是工具,想法和問題 才是重點







聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.