iphone - 从 Localizable.strings 文件中读取作为字典中的键值 [英] iphone - reading from Localizable.strings file as a key-value in a dictionary

查看:30
本文介绍了iphone - 从 Localizable.strings 文件中读取作为字典中的键值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从 localizable.strings 文件中读取文本.我正在从一个 .strings 文件中的多个目录和文件中收集用于翻译的字符串.但是后来我有几个相同翻译字符串的副本.我想以编程方式删除它.所以我只需要从 .strings 文件中读取字符串(而不是注释),并且- 然后对它们进行排序,- 删除重复的字符串然后创建一个新的 .strings 文件.

I want to read the text from the localizable.strings file. I am collecting the strings for translation from several directories and file in one .strings file. But then I have several copies of the same translation strings. I want to remove this programmatically. So I need to read the strings only (not the comments) from the .strings file, and - then sort them, - remove repeated strings then create a new .strings file.

是否可以读取字符串文件并将关键字符串和翻译值保存在字典中.我的意思是任何读取 .text 文件的内置方法,只有key"=value"部分,避免/* ... */或 # 注释部分.就像阅读配置文件一样.

Is it possible to read the strings file and keep the key string and translated value in a dictionary. I mean any built-in method to read a .text file, only the "key " = "value" part, avoiding /* ... */ or # comments part. Like reading a config file.

推荐答案

我很高兴在 NSString 类中找到了一个优秀的 API.代码如下.

I am happy to find an excellent API in NSString class. The code is below.

- (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:@""%@" = "%@";
", key, [stringDictionary objectForKey:key]];
    NSLog(@"%@",line);
    [outputHandle writeData:[line dataUsingEncoding:NSUnicodeStringEncoding]];
}
}

这篇关于iphone - 从 Localizable.strings 文件中读取作为字典中的键值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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