views:

122

answers:

3

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 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?

+2  A: 

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.

balpha
Indeed. Use `for line in strings_file:` instead.
Thomas Wouters
Ah, you are right, I was using simply for file_line in strings_file:, without the read(); will edit in a moment
MihaiD
@MihaiD: `for line in file` will only work (as expected) on plain text files, which (as you say) the `.strings` files are not.
balpha
+1  A: 

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
J.F. Sebastian
Thanks, this works perfectly. Using your solution I realized some of my .strings were encoded utf-8 and most were utf-16. This probably explains why the matching worked only in some of the files.
MihaiD
A: 

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]; 
TechZen
Yes, that's one way to go. Will keep in mind if all else fails.
MihaiD