简体   繁体   中英

Having trouble translating strings

I've decided to start on a project over spring break, taking characters from a webcomic and translating text as if that character was saying it. I've managed to get it to work well for one character, but there's a slight problem.

def meulin():
    replace = {'EE':'33', 'ee':'33'}
    originalText = input('Input text -> ')
    while True:
        for i, j in replace.items():
            if i in originalText:
                newText = originalText.replace(i,j)
                print(newText.upper())
            else:
                print(originalText.upper())
        originalText = input('Input text (type "quit" to end program.) -> ')
        if originalText in ('quit', 'end', 'exit', 'stop', 'q'):
            sys.exit('Program ended.')

When I ran PyScripter's debugger, it told me that after getting input, the program starts at the for i, j in replace.items(): line, skips the if statement completely and goes to the else statement, then goes to the if statement. So instead of just posting

CH33SE

it'll post

CHEESE

CH33SE

I could just remove the else statement completely, but then it wouldn't post the original text at all. Any suggestions would be appreciated.

for i, j in replace.items():
    if i in originalText:
        newText = originalText.replace(i,j)
        print(newText.upper())
        break
else:
    print(originalText.upper())

The break statement means the loop will stop after the first substitution. Python allows an else clause on a for loop which will execute only if the loop is not stopped by a break statement.

The reason you saw the output twice is because you have two items in your dict. I think you are looking to print the original text only when none of the substitutions match.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM