我在Google的Colab.Research平台上成功运行了Python 3 / Spark 2.2.1程序:
!apt-get update
!apt-get install openjdk-8-jdk-headless -qq > /dev/null
!wget -q http://apache.osuosl.org/spark/spark-2.2.1/spark-2.2.1-bin-hadoop2.7.tgz
!tar xf spark-2.2.1-bin-hadoop2.7.tgz
!pip install -q findspark
import os
os.environ["JAVA_HOME"] = "/usr/lib/jvm/java-8-openjdk-amd64"
os.environ["SPARK_HOME"] = "/content/spark-2.2.1-bin-hadoop2.7"
import findspark
findspark.init()
from pyspark.sql import SparkSession
spark = SparkSession.builder.master("local[*]").getOrCreate()
当我使用
将文本文件从本地计算机上传到Unix VM时,这非常有效from google.colab import files
datafile = files.upload()
并按如下方式阅读:
textRDD = spark.read.text('hobbit.txt').rdd
当我尝试读取位于Google云台驱动器colab目录中的文件时,我的问题就出现了。
按照说明我已对用户进行了身份验证并创建了驱动器服务
from google.colab import auth
auth.authenticate_user()
from googleapiclient.discovery import build
drive_service = build('drive', 'v3')
之后我能够访问位于驱动器中的文件,如下所示:
file_id = '1RELUMtExjMTSfoWF765Hr8JwNCSL7AgH'
import io
from googleapiclient.http import MediaIoBaseDownload
request = drive_service.files().get_media(fileId=file_id)
downloaded = io.BytesIO()
downloader = MediaIoBaseDownload(downloaded, request)
done = False
while done is False:
# _ is a placeholder for a progress object that we ignore.
# (Our file is small, so we skip reporting progress.)
_, done = downloader.next_chunk()
downloaded.seek(0)
print('Downloaded file contents are: {}'.format(downloaded.read()))
Downloaded file contents are: b'The king beneath the mountain\r\nThe king of ......
即使这样也很完美..
downloaded.seek(0)
print(downloaded.read().decode('utf-8'))
并获取数据
The king beneath the mountain
The king of carven stone
The lord of silver fountain ...
最近发生错误的地方是我试图获取这些数据并将其放入火花RDD
downloaded.seek(0)
tRDD = spark.read.text(downloaded.read().decode('utf-8'))
我收到了错误..
AnalysisException: 'Path does not exist: file:/content/The king beneath the mountain\ ....
显然,我没有使用正确的方法/参数将文件读入spark。我已经尝试了很多描述的方法
如果有人可以帮我弄清楚如何阅读此文件以供后续处理,我将非常感激。
答案 0 :(得分:1)
答案 1 :(得分:0)
似乎spark.read.text
需要文件名。但你改为给它文件内容。你可以尝试以下任何一种:
downloaded
代替downloaded.read().decode('utf-8')
您还可以使用pydrive简化从Google云端硬盘下载的过程。我在这里举了一个例子。
https://gist.github.com/korakot/d56c925ff3eccb86ea5a16726a70b224
下载只是
fid = drive.ListFile({'q':"title='hobbit.txt'"}).GetList()[0]['id']
f = drive.CreateFile({'id': fid})
f.GetContentFile('hobbit.txt')