【问题标题】:how can I translate my function into a more complex main() function?如何将我的函数转换为更复杂的 main() 函数?
【发布时间】:2021-02-27 08:48:48
【问题描述】:

我已经尝试了几个小时,未能成功地将这段代码转换为可以使用 main() 函数调用的独立函数

所以这段代码对我有用,但是当我尝试将它变成 if name == "ma​​in" 函数时,我不断收到错误:

filename = 'some_text.txt'
file = open(filename, 'r')
txt = file.read()
file.close()

def countwords(txt):
    import string 
    txt = txt.lower()  
    word = txt.translate(str.maketrans('', '', string.punctuation)).split()
    count = {}
    for i in word:
      if i in count:
       count[i] += 1
      else: count[i] = 1
    return count 

countwords(txt)

我怎么能把它翻译成一个读取文本的函数,另一个计算单词并通过 main() 函数执行的函数? 类似这样的结构:

def readfile(text)
    return

def wordcount(lines)
    return

def main()
    readfile(text)
    wordcount(lines)
    if __name__== "__main__" :
main()

感谢您的帮助!我希望我没有在问题中犯任何错误...

【问题讨论】:

  • 你的程序返回什么?你跑了吗?
  • 请从intro tour 重复on topichow to ask。 “告诉我如何解决这个编码问题?”与 Stack Overflow 无关。您必须诚实地尝试解决方案,然后就您的实施提出具体问题。 Stack Overflow 并不打算取代现有的教程和文档。 “尝试不成功”不是问题规范;这表明当地的导师。

标签: python main


【解决方案1】:

您可以通过将打开的文件代码编写为以下代码来节省一些代码行:

with open('some_text.txt') as file:
    file.read()

整个程序可能如下所示:

def read_file():
    with open('test_file.txt') as file:
        return file.read()


def word_count(file):
    import string
    txt = file.lower()
    word = txt.translate(str.maketrans('', '', string.punctuation)).split()
    count = {}
    for i in word:
        if i in count:
            count[i] += 1
        else:
            count[i] = 1
    return count


def main():
    wc = word_count(read_file())
    print(wc)

main()

【讨论】:

    【解决方案2】:
    text = ''
    
    def readfile(text)
        filename = 'some_text.text'
        file = open(filename, 'r')
        text = file.read()
        file.close()
        return
    
    def wordcount()
        import string 
        text = text.lower()  
        word = text.translate(str.maketrans('', '', string.punctuation)).split()
        count = {}
        for i in word:
          if i in count:
            count[i] += 1
          else: 
            count[i] = 1
        return count 
        
    
    def main()
        readfile()
        wordcount()
        
    main()    
    

    【讨论】:

      猜你喜欢
      • 2019-11-23
      • 1970-01-01
      • 1970-01-01
      • 2012-04-09
      • 1970-01-01
      • 2013-05-14
      • 1970-01-01
      • 2020-06-07
      • 1970-01-01
      相关资源
      最近更新 更多