concept word in category pyspark

appears as: words, word, words, word
Data Analysis with Python and PySpark

This is an excerpt from Manning's book Data Analysis with Python and PySpark.

Listing 2.9. Splitting our lines of text into arrays or words
from pyspark.sql.functions import split

lines = book.select(split(book.value, " ").alias("line"))

lines.show(5)

# +--------------------+
# |               value|
# +--------------------+
# |[The, Project, Gu...|
# |                  []|
# |[This, eBook, is,...|
# |[almost, no, rest...|
# |[re-use, it, unde...|
# +--------------------+
# only showing top 5 rows

Listing 2:16 contains the source code to lower the case of all the words in the data frame. The code should look very familiar: we select a column transformed by lower, a PySpark function lowering the case of the data inside the column passed as a parameter. We then alias the resulting column to word to avoid PySpark’s default nomenclature. Illustrated, it could look approximately like figure 2.5.

Listing 2.16. Lower the case of the words in the data frame
from pyspark.sql.functions import lower
words_lower = words.select(lower(col("word")).alias("word_lower"))

words_lower.show()

# +-----------+
# | word_lower|
# +-----------+
# |        the|
# |    project|
# |  gutenberg|
# |      ebook|
# |         of|
# |      pride|
# |        and|
# | prejudice,|
# |         by|
# |       jane|
# |     austen|
# |           |
# |       this|
# |      ebook|
# |         is|
# |        for|
# |        the|
# |        use|
# |         of|
# |     anyone|
# +-----------+
# only showing top 20 rows
Figure 2.5. Applying lower to a column and aliasing the resulting column: a creative explanation
lower alias

Removing punctuation and other non-useful characters can be a little trickier. We won’t improvise a full NLP (Natural Language Processing, which is an amazingly field of data analysis/science that focuses on text. We’ll cover it briefly in Chapter 9!) library here, relying on the functionality PySpark provides in its data manipulation toolbox. In the spirit of keeping this exercise simple, we’ll keep the first contiguous group of letters as the word, including apostrophes, and remove the rest. It will effectively remove punctuation, quotation marks and other symbols, at the expense of being less robust with more exotic word construction. listing 2.17 shows the code in all its splendour.