#python #apache-spark #pyspark #mapreduce
#python #apache-spark #pyspark #mapreduce
Вопрос:
Мне нужно найти все 3-граммовые черепицы в текстовом файле (спортивные статьи с заголовком и текстом) способом mapreduce. Однако файлы txt имеют формат
This is the title
Content is here on the next line.
This is another line.
Если я использую sc.textFile()
без обработки, text = sc.textFile().collect()
будет похоже
['This is the title',
'',
'Content is here on the next line.',
'',
'This is another line.']
из-за этого текстовый файл имеет несколько строк.
В результате 3-граммовое разделение будет похоже
[['This is the',
'is the title'],
[],
['Content is here',
'is here on',
'here on the',
'here on the',
'the next line.'],
[],
['This is another',
'is another line.']]
если я использую функцию map text.map(shingling)
k = 3
def shingling(text):
tokens = text.split()
shingle = [' '.join(tokens[i:i k])
for i in range(len(tokens) - k 1)]
return shingle
То, что я хочу, похоже
['This is the',
'is the title',
'the title Content',
'title Content is',
......]
и я хочу знать, есть ли какая-либо функция для использования или как я должен изменить свой код, чтобы сделать это.
Ответ №1:
Возможно, вам потребуется объединить строки, используя приведенный ниже код:
rdd = sc.textFile('text')
rdd2 = sc.parallelize([rdd.fold('', lambda x, y: x ' ' y)]).map(shingling)
>>> rdd2.collect()
[['This is the', 'is the title', 'the title Content', 'title Content is',
'Content is here', 'is here on', 'here on the', 'on the next', 'the next line.',
'next line. This', 'line. This is', 'This is another', 'is another line.']]