美文网首页
iOS 通过python脚本 找到代码里的多语言本地化key是否

iOS 通过python脚本 找到代码里的多语言本地化key是否

作者: Kpengs | 来源:发表于2024-03-04 11:50 被阅读0次

    1.写一个脚本,搜寻代码里所有的用的多语言key的地方

    import re
    import os
    
    def extract_keys_from_file(file_path):
        with open(file_path, 'r') as file:
            content = file.read()
    
            # 匹配 DEF_LOCALIZED_STRING
            matches_def_localized = re.findall(r'DEF_LOCALIZED_STRING\(key: "(.*?)"\)', content)
    
            # 匹配 self.dontHaveLabel.hc_Text = "login.createAccount"
            matches_hc_text = re.findall(r'self\.(\w+)\.hc_Text\s*=\s*"(.*?)"', content)
    
            # 匹配 signUpButton.hc_SetTitle("register.signUpBtn", for: .normal)
            matches_hc_set_title = re.findall(r'\.hc_SetTitle\("(.*?)",\s*for:\s*\.\w+\)', content)
    
            # 匹配 emailTF.hc_PlaceholderSwitch = "login.emailAddress"
            matches_hc_placeholder_switch = re.findall(r'\.hc_PlaceholderSwitch\s*=\s*"(.*?)"', content)
    
            return matches_def_localized + matches_hc_text + matches_hc_set_title + matches_hc_placeholder_switch
    
    def main():
        # 使用当前脚本所在的目录作为起始点
        script_directory = os.path.dirname(os.path.abspath(__file__))
    
        # 存储所有的 key,使用 set 来自动去重
        all_keys = set()
    
        # 遍历当前目录及其子目录下的所有 Swift 文件
        for root, dirs, files in os.walk(script_directory):
            for file in files:
                if file.endswith('.swift'):
                    file_path = os.path.join(root, file)
                    keys = extract_keys_from_file(file_path)
                    if keys:
                        all_keys.update(keys)
    
        # 输出去重后的 key
        print('Unique Keys:')
        for key in all_keys:
            if isinstance(key, tuple) and len(key) == 2:
                # 输出元组的第二个元素
                print(key[1])
            else:
                print(key)
    
    if __name__ == "__main__":
        main()
    
    

    将以上代码放到项目根目录执行后,即可得到代码里所有用到的key 并输出出来 注意

    以下部分代码是根据项目里多语言方法前缀搜索
        # 匹配 DEF_LOCALIZED_STRING
        matches_def_localized = re.findall(r'DEF_LOCALIZED_STRING\(key: "(.*?)"\)', content)
    
        # 匹配 self.dontHaveLabel.hc_Text = "login.createAccount"
        matches_hc_text = re.findall(r'self\.(\w+)\.hc_Text\s*=\s*"(.*?)"', content)
    
        # 匹配 signUpButton.hc_SetTitle("register.signUpBtn", for: .normal)
        matches_hc_set_title = re.findall(r'\.hc_SetTitle\("(.*?)",\s*for:\s*\.\w+\)', content)
    
        # 匹配 emailTF.hc_PlaceholderSwitch = "login.emailAddress"
        matches_hc_placeholder_switch = re.findall(r'\.hc_PlaceholderSwitch\s*=\s*"(.*?)"', content)
    

    根据自己的的项目会有调整

    比如自己的项目是通过

    let localizedString = NSLocalizedString("Hello", comment: "Greeting")
    

        matches_def_localized = re.findall(NSLocalizedString(\ "(.*?)"\)', content)
    

    2.写一个脚本,搜寻Localizable.strings的所有key

    import re
    import os
    
    def extract_keys_from_strings_file(file_path):
        with open(file_path, 'r', encoding='latin-1') as file:
            content = file.read()
            matches = re.findall(r'"(.*?)"\s*=\s*".*?";', content)
            return matches
    
    def main():
        # 使用当前脚本所在的目录作为起始点
        script_directory = os.path.dirname(os.path.abspath(__file__))
    
        # 存储所有的 key,使用 set 来自动去重
        all_keys = set()
    
        # 遍历当前目录及其子目录下的所有 Localizable.strings 文件
        for root, dirs, files in os.walk(script_directory):
            for file in files:
                if file == 'Localizable.strings':
                    file_path = os.path.join(root, file)
                    keys = extract_keys_from_strings_file(file_path)
                    if keys:
                        all_keys.update(keys)
    
        # 输出所有的 key
        print('All Keys in Localizable.strings:')
        for key in all_keys:
            print(key)
    
    if __name__ == "__main__":
        main()
    
    

    此文件也是放到根目录(会扫描项目所有的Localizable.strings)下,或者需要扫描的Localizable.strings的同级目录

    3.组合2个脚本,把得到的2个数组相减得到最后的结果

    import re
    import os
    
    def extract_keys_from_file(file_path):
        with open(file_path, 'r') as file:
            content = file.read()
    
    # 匹配 DEF_LOCALIZED_STRING,不管是否有 self.
        matches_def_localized = re.findall(r'(?:self\.)?DEF_LOCALIZED_STRING\(key: "(.*?)"\)', content)
    
    # 匹配不管是否有 self. 的情况,例如:dontHaveLabel.hc_Text = "login.createAccount" 或 self.dontHaveLabel.hc_Text = "login.createAccount"
        matches_hc_text = re.findall(r'(?:self\.)?(\w+)\.hc_Text\s*=\s*"(.*?)"', content)
    
    # 匹配不管是否有 self. 的情况,例如:signUpButton.hc_SetTitle("register.signUpBtn", for: .normal)
        matches_hc_set_title = re.findall(r'(?:self\.)?\.hc_SetTitle\("(.*?)",\s*for:\s*\.\w+\)', content)
    
    # 匹配不管是否有 self. 的情况,例如:emailTF.hc_PlaceholderSwitch = "login.emailAddress"
        matches_hc_placeholder_switch = re.findall(r'(?:self\.)?\.hc_PlaceholderSwitch\s*=\s*"(.*?)"', content)
    
        return matches_def_localized + matches_hc_text + matches_hc_set_title + matches_hc_placeholder_switch
    
    
    def extract_keys_from_strings_file(file_path):
        with open(file_path, 'r', encoding='latin-1') as file:
            content = file.read()
            matches = re.findall(r'"(.*?)"\s*=\s*".*?";', content, re.DOTALL)
            return matches
    
    def main():
        # 使用当前脚本所在的目录作为起始点
        script_directory = os.path.dirname(os.path.abspath(__file__))
    
        # 存储所有的项目 key,使用 set 来自动去重
        project_keys = set()
    
        # 存储所有的 Localizable.strings key,使用 set 来自动去重
        localizable_keys = set()
    
        # 遍历当前目录及其子目录下的所有 Swift 文件
        for root, dirs, files in os.walk(script_directory):
            for file in files:
                if file.endswith('.swift'):
                    file_path = os.path.join(root, file)
                    # print(f"处理Swift文件:{file_path}")
                    keys = extract_keys_from_file(file_path)
                    # print(f"找到的键:{keys}")
                    if keys:
                        # 处理可能是元组的情况,取元组的第2位
                        project_keys.update(key[1] if isinstance(key, tuple) else key for key in keys)
    
        # 遍历当前目录及其子目录下的所有 Localizable.strings 文件
        for root, dirs, files in os.walk(script_directory):
            for file in files:
                if file == 'Localizable.strings':
                    file_path = os.path.join(root, file)
                    keys = extract_keys_from_strings_file(file_path)
                    if keys:
                        localizable_keys.update(keys)
    
    
        print("项目 keys:")
        print(project_keys)
    
        print("\nLocalizable.strings keys:")
        print(localizable_keys)
        # 寻找在项目中但不在 Localizable.strings 中的 key
        missing_keys = project_keys - localizable_keys
    
        print("\nmissing_keys:")
        print(missing_keys)
    
        # 输出结果
        # print("Keys in project but not in Localizable.strings:")
        keys_array = list(missing_keys)
        if keys_array:
            print("扫描结果 --- Localizable.strings文件缺失的key: " + "   |   ".join(keys_array))
        else:
            print("扫描结果 --- Localizable.strings文件里没有缺失的key")
    
    if __name__ == "__main__":
        main()
    
    

    相关文章

      网友评论

          本文标题:iOS 通过python脚本 找到代码里的多语言本地化key是否

          本文链接:https://www.haomeiwen.com/subject/zralzdtx.html