【问题标题】:How to make python read all files in directory for a dictionary?如何让python读取字典目录中的所有文件?
【发布时间】:2019-09-28 23:52:18
【问题描述】:

我在一个文件夹中有 20 个文本文件的集合,我正在尝试为其创建字典并将字典输出到文本文件。

我通过输入文件名创建了一个适用于目录中单个文件的代码。但是它不允许我一次输入多个文本文件,如果我单独运行每个文件,它们只会相互覆盖。我尝试将文件输入转换为使用 import os 并从我的 cwd 中读取,但我遇到了变量错误,我只是不确定我做错了什么。

fname = input ('Enter File: ')
hand = open(fname)

di = dict()
for lin in hand:
    lin = lin.rstrip()
    wds = lin.split()
    for w in wds:


        di[w] = di.get(w,0) + 1

print(di)


largest = -1
theword = None
for k,v in di.items() : 
    if v > largest : 
        largest = v
        theword = k

print(theword,largest)

f = open("output.txt", "w")
f.write(str(di))
f.close()

我尝试添加

import os
for filename in os.listdir(os.getcwd()):
    fname = ('*.txt')
    hand = open(fname)

到顶部,但我出错了,因为它没有识别出我认为将 fname 分配为它正在读取的文件的通配符。

【问题讨论】:

  • 您似乎正在计算文件中的单词并计算它们的频率。这是collections.Counter 的完美案例。

标签: python dictionary


【解决方案1】:

如果你想使用通配符,你需要glob 模块。但是在您的情况下,听起来您只想将所有文件放在一个目录中,所以:

for filename in os.listdir('.'): # . is cwd
    hand = open(filename)

【讨论】:

    【解决方案2】:

    您可以遍历目录中的每个 .txt 文件,并将这些文本文件的内容打印或存储在字典或变量中。

    import os
    
    for filename in os.listdir(os.getcwd()):
             name, file_extension = os.path.splitext(filename)
             if '.txt' in file_extension:
                    hand = open(filename)
                    for line in hand:
                        print line
    

    【讨论】:

      【解决方案3】:
      import glob
      
      # a list of all txt file in the current dir
      files = glob.glob("*.txt")
      
      # the dictionary that will hold the file names (key) and content (value)
      dic = {}
      # loop to opend files
      for file in files:
          with open(file, 'r', encoding='utf-8') as read:
              # the key will hold the name the value the content
              dic[file] = read.read()
              # For each file we will append the name and the content in output.txt
              with open("output.txt", "a", encoding = 'utf-8') as output:
                  output.write(dic[file] + "\n" + read.read() + "\n\n")
      

      【讨论】:

        【解决方案4】:

        如果您使用 Python 3.4 或更高版本,您的代码可以通过使用 pathlib.Path()collections.Counter() 来非常简化:

        from pathlib import Path
        from collections import Counter
        
        counter = Counter()
        dir = Path('dir')
        out_file = Path('output.txt')
        
        for file in dir.glob('*.txt'):
            with file.open('r', encoding='utf-8') as f:
                for l in f:
                    counter.update(l.strip().split())
        
        counter.most_common(10)
        
        with out_file.open('w', encoding='utf-8') as f:
            f.write(counter)
        

        如果您使用的是 Python 3.5 或更高版本,则该代码可以更加简单:

        from pathlib import Path
        from collections import Counter
        
        counter = Counter()
        dir = Path('dir')
        out_file = Path('output.txt')
        
        for file in dir.glob('*.txt'):
            counter.update(file.read_text(encoding='utf-8').split())
        
        counter.most_common(10)
        out_file.write_text(counter, encoding='utf-8')
        

        这是作为示例输出:

        >>> from pathlib import Path
        >>> from collections import Counter
        >>> counter = Counter()
        >>> file = Path('t.txt')
        >>> file.is_file()
        True
        >>> with file.open('r', encoding='utf-8') as f:
        ...     for l in f:
        ...             counter.update(l.strip().split())
        ... 
        >>> counter.most_common(5)
        [('is', 10), ('better', 8), ('than', 8), ('to', 5), ('the', 5)]
        >>> 
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2014-11-10
          • 1970-01-01
          • 2013-12-02
          • 2019-11-13
          • 2013-09-28
          • 2021-11-06
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多