Jupyter notebook 如何在google Collab中打开文本文件

Jupyter notebook 如何在google Collab中打开文本文件,jupyter-notebook,python-3.5,google-colaboratory,Jupyter Notebook,Python 3.5,Google Colaboratory,我最近正在使用google collab juypter笔记本。上传文本文件后,无法使用python 3中的open函数打开该文件 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,

我最近正在使用google collab juypter笔记本。上传文本文件后,无法使用python 3中的open函数打开该文件

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:应该是str、bytes或os.PathLike对象,而不是_io.StringIO


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

io.StringIO指的是StringIO对象(内存文件流)。“对于字符串,StringIO可以像在文本模式下打开的文件一样使用。”

问题是文件已经打开,您可以将其作为StringIO缓冲区使用。我认为您需要在StringIO对象(数据路径)上执行readlines()

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

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

更改为

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)

工作。但是要注意读取字节的数据类型('rb');可能要使用“r”引入str数据类型。看看这里的例子。。。