2017-11-11 78 views
-1

高清转换(字符串翻译):转换字到其它字保持原来的格式

''' 
>>> translations = {'he':'she', 'brother':'sister'} 
>>> translate('he', translations) 
'she' 
>>> translate('HE', translations) 
'SHE' 
>>> translate('He', translations) 
'She' 
>>> translate('brother', translations) 
'sister' 
>>> translate('my', translations) 
'my' 
''' 

我有这样的投入。我用translations.get(字符串)让他和妹妹,它运作良好。但事情是我不能将字符串转换为'她'或'他'(原始格式)。 如何在Python中做到这一点?

+1

你可以用'str.lower ()'/'str.title()'按照要求 – ksai

回答

1

您将需要不得不采取更大的字典,大小写敏感的,或者你的翻译功能将不得不被修改为:

  1. 检测原词或短语的情况下,所有较低,全部较高,句子或标题。
  2. 查找翻译不区分大小写
  3. 重新情况下翻译文本,以匹配原始。

一些语言,你仍然会有一些问题,如:在一些语言全部大写包括一些小写字母有时还是大写的第二个字母,而不是第一如d”为前缀会总是小写或者具有不同的大写规则,国际单位制中的英国的大写规则说如果单位是以某人命名的话,它应该总是大写,但其他国家则以不同的方式做。

1

正如你翻译的数据结构,我们可以建立的情况下,测试和修正的数据结构:

def iscapitalized(s): 
    return s and s[0].isupper() and s[1:].islower() 

def translate(string, translations): 
    translation = translations.get(string.lower(), string) 

    for test, correction in corrections.items(): 
      if test(string): 
       translation = correction(translation) 
       break 

    return translation 

translations = {'he': 'she', 'brother': 'sister'} 

corrections = {str.isupper: str.upper, str.islower: str.lower, iscapitalized: str.capitalize} 

print(translate('he', translations)) 
print(translate('HE', translations)) 
print(translate('He', translations)) 
print(translate('brother', translations)) 
print(translate('my', translations)) 

输出

> python3 test.py 
she 
SHE 
She 
sister 
my 
>