iPhone-从lotizable.strings文件中读取作为字典中的键值
-
01-10-2019 - |
题
我想从lotizable.strings文件中阅读文本。我正在从一个.strings文件中收集从几个目录的翻译字符串。但是后来我有几份相同翻译字符串的副本。我想编程删除此。因此,我需要仅读取.strings文件中的字符串(而非注释),然后 - 然后 - 对它们进行排序 - 删除重复的字符串,然后创建一个新的.strings文件。
是否可以读取字符串文件并将键字符串和翻译值保持在字典中。我的意思是任何读取.TEXT文件的内置方法,仅“键” =“ value”部分,避免 / * ... * /或#注释部分。喜欢阅读配置文件。
解决方案 2
我很高兴在NSString课程中找到出色的API。代码在下面。
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
// Insert code here to initialize your application
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"Localizable" ofType:@"strings"];
NSString *fileText = [NSString stringWithContentsOfFile:filePath encoding: NSUnicodeStringEncoding error:nil];
NSDictionary *stringDictionary = [fileText propertyListFromStringsFileFormat];
NSArray *allKeys = [stringDictionary allKeys];
NSArray *sortedKeys = [allKeys sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];
NSString *documentsDirectory;
NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
if ([paths count] > 0) {
documentsDirectory = [paths objectAtIndex:0];
}
NSString *outputPath = [documentsDirectory stringByAppendingString:@"/Localizable.strings"];
NSLog(@"Strings contents are writing to: %@",outputPath);
[[NSFileManager defaultManager] createFileAtPath:outputPath contents:nil attributes:nil];
NSFileHandle *outputHandle = [NSFileHandle fileHandleForWritingAtPath:outputPath];
[outputHandle seekToEndOfFile];
for(id key in sortedKeys){
NSString *line = [NSString stringWithFormat:@"\"%@\" = \"%@\";\n", key, [stringDictionary objectForKey:key]];
NSLog(@"%@",line);
[outputHandle writeData:[line dataUsingEncoding:NSUnicodeStringEncoding]];
}
}
其他提示
NSString *path = [[NSBundle mainBundle] pathForResource:@"Localizable"
ofType:@"strings"
inDirectory:nil
forLocalization:@"ja"];
// compiled .strings file becomes a "binary property list"
NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:path];
NSString *jaTranslation = [dict objectForKey:@"hello"];
迅速解决方案
我根据 @jason-moore回答的Objective-C代码创建了一个快速代码 多于该解决方案是迅速等效的。
guard let path = Bundle.main.url(forResource: "Localizable", withExtension: "strings", subdirectory: nil, localization: "ja") else {
return nil
}
guard let dict = NSDictionary(contentsOf: path) else {
return nil
}
guard let jaTranslation = dict.value(forKey: "hello") as? String else {
return nil
}
我正在寻找的是一种从捆绑文件读取JSON的方法 NSDictionary
然后将其打印在一个 UITextView
。结果的格式不佳!
我从上面使用了Karim答案的一部分来创建一种在字符串中生成美化JSON的方法:
-(void)setText:(NSDictionary *)json
{
NSArray *allKeys = [json allKeys];
_beautyStr = @"";
for(id key in allKeys){
NSString *line = [NSString stringWithFormat:@"\"%@\" = \"%@\";\n", key, [text objectForKey:key]];
_beautyStr = [NSString stringWithFormat:@"%@%@",_beautyStr, line];
}
NSLog(@"%@",_beautyStr);
}
不隶属于 StackOverflow