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

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

问题描述

我想从localizable.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部分,避免使用/ * ... * /或#views部分。就像阅读配置文件一样。

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

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

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