【问题标题】:How to read multiple text files as strings from two folders at the same time using readline() in python?python - 如何在python中使用readline()同时从两个文件夹中读取多个文本文件作为字符串?
【发布时间】:2020-08-07 08:41:19
【问题描述】:

目前有以下脚本的版本,它使用两个简单的 readline() sn-ps 从两个不同的文件夹读取单行 .txt 文件。在ubuntu 18.04和python 3.67下运行不使用glob。

现在尝试使用“sorted.glob”从同一文件夹中读取多个文本文件时遇到“NameError”

readlines() 会导致错误,因为来自 .txt 文件的输入必须是字符串而不是列表。

python 新手。尝试过在线python格式化、reindent.py等都没有成功。

希望这是一个简单的缩进问题,因此在以后的脚本中不会成为问题。

来自以下代码的当前错误:

Traceback (most recent call last):
  File "v1-ReadFiles.py", line 21, in <module>
    context_input = GenerationInput(P1=P1, P3=P3,
NameError: name 'P1' is not defined

当前修改的脚本:

import glob
import os

from src.model_use import TextGeneration
from src.utils import DEFAULT_DECODING_STRATEGY, LARGE
from src.flexible_models.flexible_GPT2 import FlexibleGPT2
from src.torch_loader import GenerationInput

from transformers import GPT2LMHeadModel, GPT2Tokenizer

for name in sorted(glob.glob('P1_files/*.txt')):
    with open(name) as f:
        P1 = f.readline()

for name in sorted(glob.glob('P3_files/*.txt')):
    with open(name) as f:
        P3 = f.readline()

if __name__ == "__main__":

    context_input = GenerationInput(P1=P1, P3=P3,
                                    genre=["mystery"],
                                    persons=["Steve"],
                                    size=LARGE,
                                    summary="detective")

    print("PREDICTION WITH CONTEXT WITH SPECIAL TOKENS")
    model = GPT2LMHeadModel.from_pretrained('models/custom')
    tokenizer = GPT2Tokenizer.from_pretrained('models/custom')
    tokenizer.add_special_tokens(
        {'eos_token': '[EOS]',
         'pad_token': '[PAD]',
         'additional_special_tokens': ['[P1]', '[P2]', '[P3]', '[S]', '[M]', '[L]', '[T]', '[Sum]', '[Ent]']}
    )
    model.resize_token_embeddings(len(tokenizer))
    GPT2_model = FlexibleGPT2(model, tokenizer, DEFAULT_DECODING_STRATEGY)

    text_generator_with_context = TextGeneration(GPT2_model, use_context=True)

    predictions = text_generator_with_context(context_input, nb_samples=1)
    for i, prediction in enumerate(predictions):
        print('prediction n°', i, ': ', prediction)

【问题讨论】:

    标签: python-3.x linux file-io glob


    【解决方案1】:

    在此感谢 afghanimah:

    Problem with range() function when used with readline() or counter - reads and processes only last line in files

    掉落的球体。还在'with open ...'之前移动了所有model=等加载函数

    with open("data/test-P1-Multi.txt","r") as f1, open("data/test-P3-Multi.txt","r") as f3:     
      for i in range(5):
        P1 = f1.readline()
        P3 = f3.readline()
    
        context_input = GenerationInput(P1=P1, P3=P3, size=LARGE)
        etc.
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-06-25
      • 2016-10-09
      • 1970-01-01
      • 2019-11-28
      • 1970-01-01
      • 2014-01-17
      • 2023-02-08
      相关资源
      最近更新 更多