如何在 google 协作中打开文本文件

how to open Text File in google Collab

我最近在使用google collab juypter notebook.After上传文本文件,无法使用python中的打开功能打开文件 3.

from google.colab import files
import io

uploaded = files.upload()

for fn in uploaded.keys():
  print('User uploaded file "{name}" with length {length} bytes'.format(
      name=fn, length=len(uploaded[fn])))
data_path = io.StringIO(uploaded['fra.txt'].decode('utf-8'))
with open(data_path, 'rb') as f:
    lines = f.read().split('\n')

但它给出了这个错误:TypeError: expected str, bytes or os.PathLike object, not _io.StringIO

如何在 google collab juypter notebook 中打开文本文件?

_io.StringIO指的是StringIO对象(内存文件流)。 "For strings StringIO can be used like a file opened in text mode."

问题是文件已经打开并且您可以将其作为 StringIO 缓冲区使用。我认为您想对 StringIO 对象执行 readlines() (data_path).

您还可以在对象上调用getvalue() 并获取整个缓冲区的str。

https://docs.python.org/3/library/io.html#io.StringIO

在这里看我的例子;我从你的代码开始...

https://colab.research.google.com/drive/1Vbh13FVm02HMXeHXx-Zko1pFpqyp7bwI

改为仅

data_path = 'fra.txt'

应该可以。

喜欢这样

with open('anna.txt', 'r') as f:    
   text=f.read()
vocab = sorted(set(text)) 
vocab_to_int = {c: i for i, c in enumerate(vocab)}    
int_to_vocab = dict(enumerate(vocab))    
encoded = np.array([vocab_to_int[c] for c in text], dtype=np.int32)