Parse .strings file with Python
I'm trying to write a small Python script to parse the .strings file in my iPhone application project and determine which keys might not be in use. I'm, also doing some string matching to filter out some of the results. This is where my开发者_如何学Python problems start :). If I try something like
for file_line in strings_file:
if 'search_keyword' in file_line:
...
the search keyword will often not match, even though if I print every file line in the same for I seem to be reading the text correctly and my search keywords appear.
The problem is these .strings files are in some binary format. Does anyone know of a proper way to parse these files?
Use correct encoding to open the .strings
-file and in your source code. According to documentation the encoding of your file could be utf-16.
# -*- coding: utf-8 -*-
import codecs
for line in codecs.open(u'your_file.strings', encoding='utf-16'):
if u'keyword' in line:
# process line
No experience with those .strings
files, but here is the reason why you don't find matches:
strings_file.read()
returns a string with the full content of the file. Iterating over a string iterates over single characters, i.e. in your for
loop, file_line
isn't a line, it's always just one single character (a string of length 1), which obviously can't contain a multi-character search word.
It sounds like the stings file was saved as data. If python can't read it as is you can convert it to a plain text file in Objective-c.
Just: (1) read the strings file into a file with the proper encoding. (2) Convert to dictionary (3) write dictionary to another file.
So:
NSString *strings=[NSString stringWithContentsOfFile:filePath encoding:NSUTF16StringEncoding error:&error];
NSDictionary *dict=[strings propertyList];
[dict writeToFile:anotherFilePath atomically:NO];
精彩评论