使用一个文件中的文本行作为其他文件的文件名

原文标题Use text lines in one file as filename for others

我的脚本读取两个文件作为输入:articles.txt 和 article-titles.txt

articles.txt contains articles that are delimited with “<<<” without quotes.While article-titles.txt contain a list of titles delimited “\n” without the quotes。The last one may or may not be delimited with a \n

articles.txt:

This is article.txt. This is article.txt. This is article.txt.
This is article.txt. This is article.txt. This is article.txt.
This is article.txt.This is article.txt. This is article.txt. This is article.txt.
>>>

This is article.txt.This is article.txt. This is article.txt.
This is article.txt. This is article.txt. This is article.txt.
This is article.txt. This is article.txt. This is article.txt.
This is article.txt. This is article.txt. This is article.txt.
>>>

This is article.txt. This is article.txt. This is article.txt. This is article.txt.
This is article.txt. This is article.txt. This is article.txt.This is article.txt.

文章标题.txt:

This is the filename of the first article
This is the filename of the second article
This is the filename of the third article

我的脚本应该将articles.txt中的文章拆分为单独的文本文件。根据article-title.txt上的每一行命名每个文件。用破折号“-”填充文件名中的每个字符空间文件名应该以.txt结尾

因此,脚本的成功执行应该包含三个文件或所需的任意数量的文件,并且将命名一个文件:This-is-the-filename-of-the-first-article.txt

目前我的脚本输出一个文件

with open("inputfile.txt", "r") as f1, open("inputfile-title.txt", "r") as f2:
    buff = []
    i = 1
    for line1, line2 in zip(f1, f2):
        x = 0
        if line1.strip():
           buff.append(line1)
        if line1.strip() == ">>>":
           data = f2.readlines()
           output = open('%s.txt' % data[x].replace('\n', ''),'w')
           output.write(''.join(buff))
           output.close()
           x+=1
           print("This is x:", x)
           print("This is data:", data)
           buff = [] #buffer reset

原文链接:https://stackoverflow.com//questions/71465891/use-text-lines-in-one-file-as-filename-for-others

回复

我来回复
  • tripleee的头像
    tripleee 评论

    直接的缺陷是您在第一次看到分隔符时读取了所有文章名称,然后进一步尝试从同一文件句柄读取将不再有效。另请参阅为什么我不能在打开的文件上调用 read() 两次?

    为了效率和优雅,我还将重构为一次简单地读取和写入一行。

    with open("articles.txt", "r") as text, open("article-title.txt", "r") as titles:
        for line in titles:
            filename = line.rstrip('\n').replace(' ', '-') + '.txt'
            with open(filename, 'w') as article:
                for line in text:
                    if line.strip() == '>>>':
                        break
                    article.write(line)
    

    如果文件名的数量少于输入文件中的节数,这显然不能正常工作。相反,如果文件名太多,则不会使用多余的文件名。也许更好的设计是将文件名内联到数据中,或者如果输入中没有足够的文件名,则可能设计一种生成备用文件名的机制。

    演示:https://ideone.com/hYnOzP

    2年前 0条评论
  • Szabolcs的头像
    Szabolcs 评论

    你应该把你的解析逻辑和你的写作逻辑分开。首先我会阅读文章内容并解析它们其次我会阅读文章标题。最后我会使用收集到的信息并写出内容。

    一种可能的方法:

    with open("articles.txt") as articles_fp:
        articles = [article.strip() for article in articles_fp.read().split(">>>")]
    
    with open("article-title.txt") as article_title_fp:
        article_titles = [
            title_line.strip() for title_line in article_title_fp if title_line.strip()
        ]
    
    for article_title, article in zip(article_titles, articles):
        with open(article_title, "w") as article_fp:
            article_fp.write(article)
    
    2年前 0条评论
  • Rowshi的头像
    Rowshi 评论

    首先从您的 article-titles.txt 文件中将您的标题读入一个列表。

    然后,当您阅读您的articles.txt文件时,您可以从列表中拉出(或弹出)您的标题。

    下面简单地产生标题,因为它贯穿articles文件。

    def get_title():
        with open('titles.txt', 'r') as f:
            yield f.readline().strip()
    
    idx = 0
    with open('articles.txt', 'r') as f:
        articles = [
            {'title': get_title(), 'lines': []},
        ]
        for line in f.readlines():
            if line.strip() == ">>>":
                articles.append(
                    {'title': get_title(), 'lines': []}
                )
                idx += 1
            else:
                articles[idx]['lines'].append(line.strip())
    
    2年前 0条评论
  • blarg的头像
    blarg 评论

    您的代码行为方式将取决于输入,因此很难准确复制您的情况。但是,有一些潜在的问题。

    您当前正在同时按行搜索两个文件。但是,由于它们的线条不是 1:1 排列的,所以您会遇到问题(f1完成时,f1仍在读取线条)。你不与f2交互,除了readlines(),它会抓取文件中从文件中当前(移动)位置开始的所有行,这不是你想要的。将一些打印语句添加到您的代码中,您将看到它的行为方式。

    相反,我建议分别遍历这2个文件,然后以独特的方式拆分这两个文件更清晰。这里有一个选项。因为你知道f1被<<<分隔,一个选项是先读取整个文件(如果不是太大),然后在这个deliniation上使用string.split()函数。然后你可以直接将f2的每一行匹配到f1的拆分输出。

    2年前 0条评论
  • Sync271的头像
    Sync271 评论

    我认为你有点复杂,这应该工作:

    with open("articles.txt", "r") as f1, open("article-title.txt", "r") as f2:
        files = f2.read().split("\n")
        data = f1.read().split(">>>\n\n")
    
    for file, datum in zip(files, data):
        file_name = file.replace(" ", "-")
        with open(f"{file_name}.txt", "w") as f:
            f.write(datum)
    
    2年前 0条评论