【问题标题】:Call function in a new function在新函数中调用函数
【发布时间】:2021-07-27 13:52:07
【问题描述】:

我有一个函数:

def get_translations(string):
    """stuff"""
    list1 = []
    empty = []
    lines = string.splitlines()
    order = 1 if string.split(',')[0] == "english" else -1
    
    if 'english,māori' in string:
        for seperate_words in lines:
            list1.append(tuple(seperate_words.split(",")[::order]))
        return list1[1:]
    
    if 'māori,english' in string:
        for seperate_words in lines:
            list1.append(tuple(seperate_words.split(",")[::order]))
        return list1[1:]    
    
    else:
        print("Header language not recognized!")
        return empty

我正在尝试在新函数 get_translations_from_file 中调用此函数,以便执行第一个函数的意图。这是因为我试图打开一个文件并将该文件用作第一个函数的字符串。这是我尝试调用的第一个函数,但没有成功:

def get_translations_from_file(filename):
    """stuff"""
    file = open(filename)
    string = file.read()
    get_translations(string)

测试是:

filename = 'places.txt'
for terms in get_translations_from_file(filename):
    print(terms)

文件内容为:

english,māori
New Zealand,Aotearoa
North Island,Te Ika-a-Māui
South Island,Te Waipounamu
Wellington,Te Whanganui a Tara
Christchurch,Ōtautahi
Hamilton,Kirikiriroa
Auckland,Tāmaki Makaurau

【问题讨论】:

    标签: python python-3.x function


    【解决方案1】:

    您正在调用get_translations,但忽略了返回值。由于get_translations_from_file 没有明确的return 语句,它隐式返回None。长话短说,你需要从get_translations返回值:

    def get_translations_from_file(filename):
        """stuff"""
        file = open(filename)
        string = file.read()
        return get_translations(string) # Here!
    

    【讨论】:

    • 感谢这工作,但现在它导致“无法识别标题语言!”但是应该承认。结果应该是 ('New Zealand', 'Aotearoa'), ('North Island', 'Te Ika-a-Māui'),...你对这是为什么有任何想法吗?
    猜你喜欢
    • 1970-01-01
    • 2023-02-22
    • 2020-02-12
    • 1970-01-01
    • 1970-01-01
    • 2014-02-14
    • 2018-06-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多