[英]Remove special characters from the start and end of a word while counting the words in a file
[英]Counting Words while including special characters and disregarding capitilization in Pyspark?
我正在做一個了解 PySpark 的小項目,我試圖讓 PySpark 對 txtfile 中的單詞執行以下操作; 它應該“忽略”單詞大寫的任何變化(即,While 與 while)並且它應該“忽略”可能出現在單詞末尾的任何其他字符(即,orange vs orange, vs orange. vs orange? ) 並將它們都算作同一個詞。
我相當肯定某種 lambda 函數或正則表達式是必需的,但我不知道如何對其進行足夠的概括,以至於我可以將任何類型的文本文件(例如一本書)放入其中並讓它返回正確的分析。
到目前為止,這是我的代碼:
import sys
from pyspark import SparkContext, SparkConf
input = sc.textFile("/home/user/YOURFILEHERE.txt")
words = input.flatMap(lambda line: line.split(" "))
wordCounts = words.map(lambda word: (word, 1)).reduceByKey(lambda a,b:a +b)
wordCounts.collect()
我需要做的最后一件事是對單詞進行頻率分析(即“While”這個詞出現的時間為 80%),但我相當確定如何做到這一點,並且目前正在將其添加到我擁有的內容中現在; 我只是在大寫和特殊字符包含方面遇到了很多問題。
關於這個問題的任何幫助,即使只是指導也會很棒。 謝謝你們!
只需用您的文本文件替換輸入,關鍵是函數word_munge
import string
import re
def word_munge(single_word):
lower_case_word=single_word.lower()
return re.sub(f"[{re.escape(string.punctuation)}]", "", lower_case_word)
input_string="While orange, while orange while orange."
input_rdd = sc.parallelize([input_string])
words = input_rdd.flatMap(lambda line: line.split(" "))
(words.
map(word_munge).
map(lambda word: (word, 1)).
reduceByKey(lambda a, b: a+ b)
).take(2)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.