Skip to content

feat: implement NSLocalizedString - #24

Open
RieLCho wants to merge 1 commit into
MaaAssistantArknights:masterfrom
RieLCho:master
Open

feat: implement NSLocalizedString#24
RieLCho wants to merge 1 commit into
MaaAssistantArknights:masterfrom
RieLCho:master

Conversation

@RieLCho

@RieLCho RieLCho commented Sep 15, 2024

Copy link
Copy Markdown
Contributor
스크린샷 2024-09-15 오후 9 53 37

So I tried to implement NSLocalizedString, which I issued earlier (MaaAssistantArknights/MaaAssistantArknights#8770)

but I think I failed to collect all of the hardcoded chinese.

python

import os
import re

def find_and_replace_hardcoded_strings(directory, localizable_file, log_file):
    # 정규 표현식을 수정하여 하드코딩된 문자열만을 정확히 찾아냅니다.
    pattern = re.compile(r'(?<!NSLocalizedString\()\"([^\"]+?)\"(?!\s*comment:)')
    hanzi_pattern = re.compile(r'[\u4e00-\u9fff]')
    localizable_strings = {}
    changes_log = []
    exclude_strings = [')', '(', '+', ':', ',']

    # Step 1: Find hardcoded strings and add to Localizable.strings
    for root, _, files in os.walk(directory):
        for file in files:
            if file.endswith(".swift"):
                file_path = os.path.join(root, file)
                with open(file_path, 'r', encoding='utf-8') as f:
                    content = f.read()
                    matches = pattern.findall(content)
                    for match in matches:
                        if match not in localizable_strings and hanzi_pattern.search(match):
                            localizable_strings[match] = match

    # Write to Localizable.strings file
    with open(localizable_file, 'w', encoding='utf-8') as f:
        for key, value in localizable_strings.items():
            f.write(f'"{key}" = "{value}";\n')

    # Step 2: Replace hardcoded strings with NSLocalizedString
    for root, _, files in os.walk(directory):
        for file in files:
            if file.endswith(".swift"):
                file_path = os.path.join(root, file)
                with open(file_path, 'r', encoding='utf-8') as f:
                    content = f.read()
                    new_content = content
                    for match in pattern.findall(content):
                        if '\n' not in match and not match.startswith('NSLocalizedString') and not any(exclude in match for exclude in exclude_strings) and hanzi_pattern.search(match):  # 한 줄에 있는 문자열만 매칭
                            new_content = new_content.replace(f'"{match}"', f'NSLocalizedString("{match}", comment: "")')
                            changes_log.append(f'"{match}"="{match}"\n')
                with open(file_path, 'w', encoding='utf-8') as f:
                    f.write(new_content)

    # Write changes log to file
    with open(log_file, 'w', encoding='utf-8') as f:
        for log in changes_log:
            f.write(log)

if __name__ == "__main__":
    find_and_replace_hardcoded_strings(".", "/Resources/zh-Hans.lproj/Localizable.strings", "/Resources/zh-Hans.lproj/Localizable.strings")

@hguandl

hguandl commented Dec 2, 2024

Copy link
Copy Markdown
Collaborator

Sorry for the delay. In SwiftUI, most Views are automatically using LocalizedStringKey. In addition, Xcode has introduced String Catalog for better localization. Therefore, I need to take some time to cherry-pick the changes. Thanks for your contribution!

@hguandl

hguandl commented Dec 2, 2024

Copy link
Copy Markdown
Collaborator

@RieLCho Hi, I have added preliminary support for i18n in 35e1c8b. Most of the localizable strings are tracked by the string catalog. To accomplish the remaining translation, please consider the following steps:

If you have Xcode 15+:

  1. Open "Resources" > "Localizable.xcstrings" in Xcode;
  2. Add translations in Xcode's friendly interface.
image

If you prefer to use a text editor:

  1. Open "Resources" > "Localizable.xcstrings" with your favorite text editor;
  2. Add translation entries, which are organized in JSON format, e.g.,
{
  "%@ HasReturned" : {                               <-- source key
    "localizations" : {
        "ko" : {
          "stringUnit" : {
            "state" : "translated",
            "value" : "%@가 돌아왔습니다"                <-- translation
          }
        }
      }
    }
}

Please IGNORE the entries with "shouldTranslate" : false.

After the translation, please submit another pull request, because this PR has too many conflicts to merge. Thanks!

@RieLCho

RieLCho commented Dec 3, 2024

Copy link
Copy Markdown
Contributor Author

Hi, @hguandl
Thanks for letting me know!
I'll work on it ASAP after school final exam (😢

Screenshot 2024-12-03 at 11 06 39 AM

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants