无法处理 IF 和变量 [已关闭]

问题描述 投票:0回答:1

我正在尝试执行以下操作:星号传输数字或一定量的文本。 我想检查是否有 10 个字符并且它们都是数字 - 将它们替换为名称。 如果还有其他内容,那就是文本,应该保持不变。 但是,由于某种原因,工作结果始终为空 - 全局变量不会被覆盖。

filename = sys.argv[1]
speech_text = sys.argv[2]
final_text = ""

def numbers_to_words(speech_text):
    if len(speech_text) == 10 and speech_text.isdecimal():
        words = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"]
        return " ".join(words[int(digit)] for digit in str(speech_text))
        final_text = numbers_to_words(speech_text)
    else:
        final_text = speech_text
print(final_text)

更新: 我尝试了建议的选项。 据我了解,我必须声明两个变量 - Final_text 和 Speech_text。 如果我尝试这样做,我会收到错误

global final_text
    ^
SyntaxError: name 'final_text' is assigned to before global declaration

怎么可能?

def numbers_to_words(speech_text):
    if len(speech_text) == 10 and speech_text.isdigit():
        global final_text
        words = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"]
        return " ".join(words[int(digit)] for digit in str(speech_text))
        final_text = numbers_to_words(speech_text)
    else:
        global final_text
        final_text = speech_text
print(final_text)

filename = sys.argv[1]
speech_text = sys.argv[2]
final_text = 0
    
def numbers_to_words():
    if len(speech_text) == 10 and speech_text.isdigit():
        global final_text
        words = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"]
        return " ".join(words[int(digit)] for digit in str(speech_text))
        final_text = numbers_to_words(speech_text)
    else:
        final_text = speech_text
print(final_text)

如果我尝试这个选项,我会得到 0 结果。 最近刚开始学习python,有些东西马上就明白了,有些东西根本就看不懂。 请帮忙

python-3.x function if-statement global-variables
1个回答
0
投票

这个版本有效

def digit_to_word(digit):
    digit_words = {'0': 'zero', '1': 'one', '2': 'two', '3': 'three', '4': 'four', '5': 'five', '6': 'six', '7': 'seven', '8': 'eight', '9': 'nine'}
    return digit_words.get(digit, digit)

def convert_numbers_to_words(number):
    return ' '.join(digit_to_word(digit) for digit in number)

def main():
    number = sys.argv[1]

    if len(number) == 10 and number.isdigit():
#    if len(str(number)) == 10 and str(number).isdigit()
        converted_number = convert_numbers_to_words(number)
        print(converted_number)
    else:
        print(number)
if __name__ == '__main__':
    main()
© www.soinside.com 2019 - 2024. All rights reserved.