~writer-devs/writer/trunk

« back to all changes in this revision

Viewing changes to resources/chardetect.py

  • Committer: Anthony Huben
  • Date: 2014-08-28 17:41:35 UTC
  • mto: This revision was merged to the branch mainline in revision 49.
  • Revision ID: harp37@gmail.com-20140828174135-c21gx6wphxh1amex
Implement Encoding.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
#!/usr/bin/env python
 
2
"""Script which takes one or more file paths and reports on their detected
 
3
encodings
 
4
 
 
5
Example::
 
6
 
 
7
    % chardetect.py somefile someotherfile
 
8
    UTF-8
 
9
    ISO-8859-1
 
10
 
 
11
If no paths are provided, it takes its input from stdin.
 
12
 
 
13
It was properly modified to fit with scratch text editor project.
 
14
Original version was from the creators of python-chardet.
 
15
 
 
16
"""
 
17
from sys import argv, stdin
 
18
 
 
19
from chardet.universaldetector import UniversalDetector
 
20
 
 
21
 
 
22
def encoding_of(file, name='stdin'):
 
23
    """Return a string describing the probable encoding of a file."""
 
24
    u = UniversalDetector()
 
25
    for line in file:
 
26
        u.feed(line)
 
27
    u.close()
 
28
    result = u.result
 
29
    if result['encoding']:
 
30
        return result['encoding'].upper ()
 
31
    else:
 
32
        return 'error'
 
33
 
 
34
 
 
35
def main():
 
36
    if len(argv) <= 1:
 
37
        print description_of(stdin)
 
38
    else:
 
39
        for path in argv[1:]:
 
40
            print encoding_of(open(path, 'rb'), path)
 
41
 
 
42
 
 
43
if __name__ == '__main__':
 
44
    main()