正则表达式:去掉连续的标点符号

2024-06-12 01:08:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图使用以下代码清除列表中的单词:

#define function to clean list of words
def clear_list(words_list):
    regex = re.compile('[\w\d]{2,}', re.U)
    filtered = [i for i in words_list if regex.match(i)]
    return filtered

clear_list_udf = sf.udf(clear_list, ArrayType(StringType()))

items = items.withColumn("clear_words", clear_list_udf(sf.col("words")))

我只需要大于1个字母的单词,不需要标点符号。但我在以下情况下遇到了问题:

我拥有的:
[“魔术师,魔术师”,魔术师,魔术师,魔术师]->
[ззззззззззззззззз

我需要什么:
[“ззззззззззззззззззззз1079 [10、10、10、10、10、10、10、10]


Tags: 代码re列表itemsfunctionsf单词filtered
2条回答

您可以使用regexp_replace,然后在df上进行过滤,以在pyspark中实现结果

我们应该尽量避免使用UDF,因为UDF就像一个黑匣子。它不能有效地对其应用优化Read more here

from pyspark.sql.functions import regexp_replace, col, length

df = df.select(regexp_replace(col("col_name"), "[^a-zA-Z0-9]", ""))
df = df.where(length(col("col_name")) >= 2)

替换此行:

filtered = [i for i in words_list if regex.match(i)]

这一行:

filtered = [regex.search(i).group() for i in words_list if regex.search(i)]

给定的正则表达式很好,但是for循环返回原始值,而不是匹配的字符串。 代码示例:

regex = re.compile('[\w\d]{2,}', re.U)
words_list = ['""word', 'wor"', 'c', "test"]
filtered = [regex.search(i).group() for i in words_list if regex.search(i)]
print(filtered)
> ['word', 'wor', 'test']

相关问题 更多 >