如何根據給定的字典翻譯 Python 字串?
要根據給定的字典翻譯 Python 字串,您可以使用 `translate()` 方法結合 `str.maketrans()` 函式。`str.maketrans()` 函式根據給定的字典建立一個翻譯表,該字典將字典中的每個字元對映到其對應的翻譯。以下是一些示例
使用字典翻譯字串
示例
字典 `translation_dict` 定義為將輸入字串中的每個字母對映到其對應的數字。我們使用 `str.maketrans()` 函式建立翻譯表,並使用 `translate()` 方法將其應用於示例字串 `text`。結果是翻譯後的字串,它用每個字母的對應數字替換每個字母。
# define a dictionary to map characters to their translations
translation_dict = {"a": "1", "b": "2", "c": "3", "d": "4"}
# define a sample string to be translated
text = "abcd"
# create a translation table using the dictionary
translation_table = str.maketrans(translation_dict)
# translate the string using the table
translated_text = text.translate(translation_table)
# print the translated string
print(translated_text)
輸出
1234
使用缺少某些鍵的字典翻譯字串
示例
在此示例中,字典 `translation_dict` 不包含字母“d”和“e”的翻譯。當 `translate()` 方法遇到這些字元時,它只是在翻譯後的字串中保持不變。
# define a dictionary to map characters to their translations
translation_dict = {"a": "1", "b": "2", "c": "3"}
# define a sample string to be translated
text = "abcde"
# create a translation table using the dictionary
translation_table = str.maketrans(translation_dict)
# translate the string using the table
translated_text = text.translate(translation_table)
# print the translated string
print(translated_text)
輸出
123de
使用包含額外字元的字典翻譯字串
示例
在此示例中,字典 `translation_dict` 不僅包含字母的翻譯,還包含空格和句點的翻譯。生成的翻譯用字典中每個字元的對應值替換每個字元,包括空格和句點,它們分別被翻譯為“-”和“!”。
# define a dictionary to map characters to their translations
translation_dict = {"a": "1", "b": "2", "c": "3", "d": "4", " ": "-", ".": "!"}
# define a sample string to be translated
text = "a b.c.d"
# create a translation table using the dictionary
translation_table = str.maketrans(translation_dict)
# translate the string using the table
translated_text = text.translate(translation_table)
# print the translated string
print(translated_text)
輸出
1-2!3!4
使用帶有字典的 `str.translate()` 方法
示例
在此示例中,我們首先建立一個字典來定義字元翻譯。然後,我們使用 `str.maketrans()` 方法建立一個翻譯表,並將字典作為引數傳遞。然後,我們使用帶有翻譯表的 `translate()` 方法來翻譯字串。輸出應為“56789”。
# create a dictionary to translate characters
translation_dict = {
"a": "5",
"b": "6",
"c": "7",
"d": "8",
"e": "9"
}
# sample string
text = "abcde"
# create a translation table from the dictionary
translation_table = str.maketrans(translation_dict)
# translate the string using the translation table
translated_text = text.translate(translation_table)
# print the translated text
print(translated_text)
輸出
56789
使用迴圈的 `str.replace()` 方法
示例
在此示例中,我們使用迴圈遍歷字典並替換字串中的每個字元。我們使用 `str.replace()` 方法將字典中鍵的每個出現替換為對應的值。輸出應為“12345”。但是,對於較大的字串和字典,此方法可能不如前面的示例有效。
# create a dictionary to translate characters
translation_dict = {
"a": "1",
"b": "2",
"c": "3",
"d": "4",
"e": "5"
}
# sample string
text = "abcde"
# loop through the dictionary and replace each character in the string
for key, value in translation_dict.items():
text = text.replace(key, value)
# print the translated text
print(text)
輸出
12345
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP