-
Notifications
You must be signed in to change notification settings - Fork 19
/
DetectorTest.m
111 lines (85 loc) · 2.82 KB
/
DetectorTest.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
#import <Foundation/Foundation.h>
#import <AppKit/AppKit.h>
#import <UniversalDetector/UniversalDetector.h>
int main(int argc,char **argv)
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
[[NSUserDefaults standardUserDefaults] setBool:YES
forKey:UniversalDetectorUseMacRomanHeuristic];
NSError *error = nil;
for (int i = 1; i < argc; i++)
{
// You need a new detector for each piece of data you want to examine!
UniversalDetector *detector = [UniversalDetector new];
NSString *filePath = [NSString stringWithUTF8String:argv[i]];
NSString *fileName = [filePath lastPathComponent];
NSData *data = [NSData dataWithContentsOfFile:filePath
options:0
error:&error];
if (data == nil) {
NSLog(@"%@", error);
continue;
}
NSString *str = nil;
if (data == nil) {
str = [NSString stringWithFormat:@"%@\n\t%@", fileName, error];
}
if (data.length == 0) {
str = [NSString stringWithFormat:@"%@\n\t%@", fileName, @"Error: empty file!"];
}
if (str) {
printf("%s\n\n", [str UTF8String]);
continue;
}
[detector analyzeData:data];
NSString *MIMECharsetName = [detector MIMECharset];
NSStringEncoding encoding = [detector encoding];
NSStringEncoding appKitEncoding = 0;
//if (encoding == NSWindowsCP1252StringEncoding || encoding == NSShiftJISStringEncoding)
{
NSDictionary *documentAttributes = nil;
// UniversalDetector does not differentiate between Windows Latin 1 and Mac Roman
// while AppKit has an apparent Mac Roman bias.
NSAttributedString *text = [[NSAttributedString alloc] initWithData:data
options:nil
documentAttributes:&documentAttributes
error:&error];
if (text == nil) {
NSLog(@"%@", error);
continue;
}
else {
[text release];
NSNumber *encodingNumber = documentAttributes[NSCharacterEncodingDocumentAttribute];
appKitEncoding = [encodingNumber intValue];
}
}
NSString *appKitResultString = nil;
if (appKitEncoding != 0) {
if (appKitEncoding != encoding) {
appKitResultString = [NSString stringWithFormat:@"\"%@\"",
[NSString localizedNameOfStringEncoding:appKitEncoding]
];
}
else {
appKitResultString = @"(same result)";
}
}
str = [NSString stringWithFormat:
@"%@\n"
"\t" "\"%@\" (%@)\n"
"\t" "confidence:% 6.1f%%"
@"\n"
"\t" "AppKit: %@",
fileName,
(encoding != 0) ? [NSString localizedNameOfStringEncoding:encoding] : @"UNKNOWN",
(MIMECharsetName != nil) ? MIMECharsetName : @"UNKNOWN",
([detector confidence] * 100.0f),
(appKitResultString != nil) ? appKitResultString : @"UNDEFINED"
];
printf("%s\n\n", [str UTF8String]);
[detector release];
}
[pool release];
return EXIT_SUCCESS;
}