【问题标题】:Wrtie a file to a new file with addition text based on criteria within source file in python根据python中源文件中的条件将文件写入带有附加文本的新文件
【发布时间】:2017-12-08 17:41:00
【问题描述】:

我正在尝试获取一个 Python 脚本,该脚本将打开一些文本文件,读取内容,每次从列表中找到一个单词时,用新文本将其屏蔽,然后将其写入一个新文件,对于每个文件。

现在,我可以让它将所有源文件写入一个文件,这是我下面的脚本,但我不确定如何继续为每个源文件创建一个新文件。

我对 python 很陌生,这很方便,所以一直用它来学习,对任何明显的错误或糟糕的代码教育表示歉意。

import os

KeyWords=["Magic","harry","wand"]

rootdir = "C:\\books"

fileslist = []


##blanks file and preps for new data
fileout = open(rootdir+"\\output\\newfile.txt","w")
print (fileout)
fileout.write("Start of file\n\nLocation of output: "+rootdir+"\\output \n\nFiles that are being Processed:\n\n")
fileout.close()



def sourcelist(fileslist):

        file=open(fileslist,"r")
        fileout=open(rootdir+"\\output\\newfile.txt", "a")

        for line in file:
                if any(word.lower() in line.lower() for word in KeyWords):
                    print("Word Found\n\n" + '\t'+line + "\nEnd\n")
                    fileout.write("<<<SEARCH TERM FOUND>>>\n\n" + '\t'+line + "\n<<<END OF BLOCK>>>\n")
                else:
                    #print('\t'+line)   #No need to print the lines with no Key words in
                    fileout.write('\t'+line)
        #return    #not sure what return does?


for root, dirs, files in os.walk(rootdir):
    dirs.clear()

    for file in files:
        filepath = root + os.sep + file
        if filepath.endswith(".txt"): 
            fileslist.append(filepath)
    for path in fileslist:
        sourcelist(path)

    print("\n".join(fileslist))    
    with open(rootdir+"\\output\\newfile.txt","a") as output:
        output.write("\n".join(fileslist)+"\n\n\n")
        output.close()

【问题讨论】:

  • 我已经阅读了你的问题 3 次,但我仍然不清楚它应该做什么。你能给出一个输入文件和预期输出的非常简短的例子吗?
  • 例如,“用新文本阻止它”。这究竟是什么意思?你的意思是把它写到一个用&lt;&lt;&lt;SEARCH TERM FOUND&gt;&gt;&gt;等封装的新文件中?
  • 在这个例子中,源文件是哈利波特书籍的摘录。 “当哈利拿到他的魔杖时,它是魔法”,然后它会在一个新目录中写入一个具有相同文件名的新文件,并且在任何看到关键字的地方,它都会添加 SEARCH TERM FOUND 字符串这是为了使它更容易读者可以看到突出显示的行。所以新的填充会显示为:当 >> Harry >> 拿到他的 >> 魔杖 >> 时>>魔术>>
  • 这将用于 60 页的文档,目前我需要花费数小时来阅读和搜索其中的关键词。
  • 好的,最后。如果没有找到关键字,您仍然会写该行的内容吗?换句话说,新文件中应该没有文本丢失,只添加了 >> 标签?

标签: python list file os.walk writing


【解决方案1】:

整体来说这有点难以回答,但这里有一个通用的方法。

我的文件结构如下:

hp_extracts: # directory
    hp_parser.py
    -- inps/
       -- harry_1.txt
       -- harry_2.txt
    -- outs/
       <nothing>

inps/harry_1.txt的内容:

When Harry got his wand it was Magic
something something magic something
something harry something

inps/harry_2.txt的内容:

magic something something
something
harry something something

这是hp_parser.py的内容:

import os

all_files = os.listdir('inps/')
keywords=["magic","harry","wand"]

for file in all_files:
    with open('inps/{}'.format(file)) as infile, open('outs/{}'.format(file), 'w') as outfile:
        for line in infile:
            #print(line)
            for word in line.split():
                if word.lower() in keywords:
                    line = line.replace(word, '<<<SEARCH TERM FOUND>>> {} <<<END OF BLOCK>>>'.format(word))
            outfile.write(line)

【讨论】:

  • 感谢您的帮助,很抱歉花了这么长时间才回复您,但我想了解它不仅仅是剪切和粘贴它。这是我第一次使用 Split() 所以需要阅读它。我现在有一个工作脚本,因此进入下一个阶段,即文件转换器,将 Word 和 PDF 转换为文本。应该很有趣:-)
猜你喜欢
  • 1970-01-01
  • 2020-08-02
  • 2021-10-17
  • 2016-08-16
  • 2013-12-26
  • 2018-11-18
  • 2023-02-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多