【问题标题】:How to iterate functions over each file in a directory如何在目录中的每个文件上迭代函数
【发布时间】:2019-07-08 19:57:29
【问题描述】:

我有适用于一个指定文件的代码。如何为多个文件迭代同一个函数?

下面的代码适用于 test3.txt 文件。我在一个文件夹中有多个文件(test1.txt、test2.txt、test3.txt ...)你能帮我遍历每个文件吗?我相信我必须更改第 6-7 行。请帮忙。我是 python 新手...

import os,csv,datefinder,re
import numpy as np

os.chdir('C:\Users\dul\Dropbox\Article')

with open("test3.txt", 'r') as file1:
      text1=file1.read()

#locate the date of the article
matches = list(datefinder.find_dates(text1))

if len(matches) > 0:
    date=matches[1]
    strdate = str(date)

else:
    print 'No dates found'


#locate the name of the company
matchcomp = re.search(r'Keywords:([^,]*)(,|$)', text1).group(1).strip()

#count the number of words in the article
matchcount = re.search(r'(.*) words', text1).group(1).strip()

#determine the article
def matchwho():
    if 'This story was generated by' in text1:
        return('1')
    elif 'This story includes elements generated' in text1:
        return('2')
    elif 'Elements of this story were generated' in text1:
        return('2')
    elif 'Portions of this story were generated' in text1:
        return('2')
    else:
        return('3')

matchw =str(matchwho())

#list the returns in a line
combid = matchcomp + "," + strdate + "," + matchw + "," + matchcount

#save in txt format
with open('outfile.txt', 'w') as outfile:
    outfile.write(combid)

我希望返回附加在 outfile.txt 中

【问题讨论】:

  • 您可以使用os.walk()(或者更可能在此处使用os.dir())返回文件夹中的所有文件名。然后将您拥有的所有代码捆绑到 def match_from_file(file) 之类的函数中,并将文件名传递给该函数
  • @Reedinationer 是否会 os.dir() 对文件夹中的所有文本文件重复该功能?我试过了,但它只是没有用....
  • 抱歉,我输入了错误的命令(dir 用于命令提示符)。您可以尝试files = os.listdir(),然后如果您想处理所有文件,您可以执行for file in files: print(file) 或者您可能想添加if ".txt" in file:,这样您就只能获取该文件夹中的文本文件。 os.walk() 将让您递归地收集文件夹中的所有文件,因此如果您的所有文件都隐藏在一系列文件夹中,您可以使用它来代替
  • @Reedinationer 问题是,尽管使用了 os.listdir(),但我的第 6-7 行已经在其中指定了“test3.txt”。这不会禁止 os.listdir() 读取文件夹中的所有文本文件吗?

标签: python python-2.7


【解决方案1】:

如何将你所有的代码打包成一个函数,每个文件可以多次调用

import os,csv,datefinder,re
import numpy as np

os.chdir('C:\Users\dul\Dropbox\Article')

def matchwho(text_to_match):
    if 'This story was generated by' in text_to_match:
        return('1')
    elif 'This story includes elements generated' in text_to_match:
        return('2')
    elif 'Elements of this story were generated' in text_to_match:
        return('2')
    elif 'Portions of this story were generated' in text_to_match:
        return('2')
    else:
        return('3')


def extract_data(filename):
    with open(filename, 'r') as file1:
        text1=file1.read()
    #locate the date of the article
    matches = list(datefinder.find_dates(text1))
    if len(matches) > 0:
        date=matches[1]
        strdate = str(date)
    else:
        print 'No dates found'
    #locate the name of the company
    matchcomp = re.search(r'Keywords:([^,]*)(,|$)', text1).group(1).strip()
    #count the number of words in the article
    matchcount = re.search(r'(.*) words', text1).group(1).strip()
    #determine the article
    matchw =str(matchwho(text1))
    #list the returns in a line
    combid = matchcomp + "," + strdate + "," + matchw + "," + matchcount
    #save in txt format
    with open('outfile.txt', 'w') as outfile:
        outfile.write(combid)

files = os.listdir()
for file in files:
    if ".txt" in file:
        extract_data(file)

*注意我没有测试此代码,因为我没有您正在处理的 .txt 文件。可能会有错误,但我认为它展示了如何获取文件名并将它们提供给处理函数。如果这解决了您的问题,如果您可以单击帖子旁边的复选标记,那就太好了:)

【讨论】:

    【解决方案2】:

    首先将第 6 行中的所有内容移到一个名为 process_file 左右的新函数中,该函数获取一个参数 filename,然后将此函数中的 text3.txt 替换为 filename

    现在你可以在脚本的末尾写了

    for f in os.listdir('C:\Users\dul\Dropbox\Article'):
        process_file(f)
    

    这样就可以了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-06-22
      • 1970-01-01
      • 1970-01-01
      • 2019-10-05
      • 2013-02-19
      • 2018-09-01
      • 1970-01-01
      相关资源
      最近更新 更多