如何创建一个用缩写替换某些单词的函数?

时间:2019-11-15 00:14:55

标签: python dictionary

因此,我需要创建一个函数,该函数从用户处获取一个字符串,然后使用全局常量,将一些单词更改为缩写形式。 PLEASE变成PLZ等。另一件事是,用户输入字符串后,它不应该询问用户是否要替换该单词,它应该自动执行。

replacements = {
'TOMORROW': 'TMR',
'ABOUT': 'BOUT',
'PLEASE': 'PLZ',
'BEFORE': 'B4',
}


def uppercase(newWord):
    new_uppercase=''
    for letters in newWord:
        if ord(letters) > 96:
            new_uppercase += chr(ord(letters)-32)
        else:
            new_uppercase += letters
    print(new_uppercase)
    return new_uppercase

def replace(newString):
    old,new = [],[]
    for ch in newString:
        if replacements.get(ch):
            newString = newString.replace(ch, replacements.get(ch))
        print(newString)

# this is the definition of your main function
def main():
    print("Hello, And Welcome to this Slang Program")
    cap_letters = input("Please enter your string here: ")  
    uppercase(cap_letters)
    # write the part of the program that interacts with the user here
    replace(uppercase(cap_letters))

# these should be the last two lines of your submission
if __name__ == '__main__':
    main()

1 个答案:

答案 0 :(得分:0)

您是否有理由尝试从头开始实现replace方法?如果不是这样,Python已经为此提供了一种绝佳的方法。您可以在任何字符串上调用str.replace

replacements = {
  'TOMORROW': 'TMR',
  'ABOUT': 'BOUT',
  'PLEASE': 'PLZ',
  'BEFORE': 'B4',
};

test_string = "PLEASE meet me TOMORROW BEFORE noon"

# loop through all replacements
for find, replace in replacements.iteritems():
  # replace the "find" key with the "replace" value
  # e.g. replace "PLEASE" (find) with "PLZ" (replace)
  test_string = test_string.replace(find, replace)

print test_string
# output: PLZ meet me TMR B4 noon