【问题标题】:How to generalize the file function to open as many text files as provided in parameter?如何概括文件功能以打开参数中提供的尽可能多的文本文件?
【发布时间】:2019-04-15 13:49:40
【问题描述】:

我想概括我的以下代码以在参数中获取尽可能多的文件而无需硬编码,例如 f1 和 f2 在这里。我怎样才能做到这一点? 这是我的代码。

def wordFreq(f1, f2):
    f1 = open(f1, 'r')  
    f2 = open(f2, 'r')
    file_list = [f1, f2]  
    num_files = len(file_list) 
    wordFreq = {} 

    .....
    .....

    return wordFreq

print(wordFreq('file1.txt','file2.txt'))

【问题讨论】:

  • 输入文件列表并循环打开,然后放入file_list

标签: python python-3.x file dictionary word-frequency


【解决方案1】:

你想要*args

def word_freq(*files):
    file_list = [open(file, 'r') for file in files]
    ...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-12-16
    • 1970-01-01
    • 1970-01-01
    • 2016-07-25
    • 1970-01-01
    • 2019-10-14
    相关资源
    最近更新 更多