Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 2.7 读取数据时如何删除unicode?_Python 2.7_Unicode_Utf 8_Apache Spark_Pyspark - Fatal编程技术网

Python 2.7 读取数据时如何删除unicode?

Python 2.7 读取数据时如何删除unicode?,python-2.7,unicode,utf-8,apache-spark,pyspark,Python 2.7,Unicode,Utf 8,Apache Spark,Pyspark,我有以下一行Python代码: trans = data.map(lambda line: line.strip().split()) 生成Unicode字符串的,例如: u'Hello',u'word' 我想要普通的UTF-8或ASCII字符串 'Hello','word' 我尝试将字符串转换为UTF-8,例如 trans = data.map(lambda line: line.strip().split().encode("utf-8")) 或 但这就产生了一个错误: Attri

我有以下一行Python代码:

trans = data.map(lambda line: line.strip().split())
生成Unicode字符串的,例如:

u'Hello',u'word'
我想要普通的UTF-8或ASCII字符串

'Hello','word' 
我尝试将字符串转换为UTF-8,例如

trans = data.map(lambda line: line.strip().split().encode("utf-8"))

但这就产生了一个错误:

AttributeError: 'list' object has no attribute 'encode'
有人能告诉我怎么做吗

更新:

数据是scv文件,
trans是RDD

您的映射函数将返回一个Unicode列表,因此您可以使用列表理解来迭代这些Unicode,并将它们转换为字符串

trans = data.map(lambda line: [str(word) for word in line.strip().split()])
尝试:


这将通过在每个元素上运行
str(element)
,将
data
中的每个元素从
unicode
转换为
str

为什么不简单地编码和拆分:

data = sc.textFile("README.md")
trans = data.map(lambda x: x.encode("ascii", "ignore").split())
trans.first()
## ['#', 'Apache', 'Spark']

为什么要避免使用Unicode?对于大多数用例来说,它应该是首选的、理智的默认值。这有点奇怪。我尽量避免使用unicode进行表示purposes@Toren这毫无意义。您的问题显示您试图编码到UTF-8,这是一种Unicode编码。这听起来仍然像是XY问题。@zero323,我使用的映射是python的内置映射,它不同,但那可能更合适,rdd.py的src-我知道,但它在这里不起作用,相信我:)rdd是不可移植的。我明白了,那就是你的答案:)
ascii = data.map(str)
data = sc.textFile("README.md")
trans = data.map(lambda x: x.encode("ascii", "ignore").split())
trans.first()
## ['#', 'Apache', 'Spark']