2016-12-31 17 views
1

string_integers.txtRDD中的主要空白来自哪里以及如何避免它?

a 1 2 3 
b 4 5 6 
c 7 8 9 

sample.py

import re 
pattern = re.compile("(^[a-z]+)\s") 

txt = sc.textFile("string_integers.txt") 
string_integers_separated = txt.map(lambda x: pattern.split(x)) 

print string_integers_separated.collect() 

结果

[[u'', u'a', u'1 2 3'], [u'', u'b', u'4 5 6'], [u'', u'c', u'7 8 9']] 

预期结果

[[u'a', u'1 2 3'], [u'b', u'4 5 6'], [u'c', u'7 8 9']] 

回答

1

拆分对在字符串的开头这样固定前缀将永远是空的字符串模式。例如,你可以使用匹配:

pattern = re.compile("([a-z]+)\s+(.*$)") 
pattern.match("a 1 2 3").groups() 
# ('a', '1 2 3') 

或回顾后:

pattern = re.compile("(?<=a)\s") 
pattern.split("a 1 2 3", maxsplit=1) 
# ['a', '1 2 3'] 

或刚刚拆分:

"a 1 2 3".split(maxsplit=1) 
# ['a', '1 2 3'] 
+0

'类型错误:拆分()不带任何关键字参数' – 030

0

目前仍然不清楚我在前面的空格来从。由于某种原因,正则表达式分割正在引入它。 Based on an example found in this documentation分裂行动创造了不引入了一个前导空格:

txt.map(lambda x: x.split(' ', 1)).collect() 
#[[u'a', u'1 2 3'], [u'b', u'4 5 6'], [u'c', u'7 8 9']] 

说明

str.split(str="", num=string.count(str))

limiting the number of splits to num

使用x.split(' ', 2)回报[[u'a', u'1', u'2 3'], [u'b', u'4', u'5 6'], [u'c', u'7', u'8 9']]

相关问题