【问题标题】:Regular expression to clean strings of words(with accents) and numbers from spaces or other characters at the beggining or end正则表达式从开头或结尾的空格或其他字符中清除字符串(带重音符号)和数字
【发布时间】:2020-01-22 11:49:40
【问题描述】:

我正在使用 python with spark 来处理一些带有葡萄牙语重音词的数据。

一些数据来的例子是这样的:

 .. -- Água, 1234 ...

 - -- https://www.example.com/page.html *****

我正在尝试从字符串的左侧或右侧删除不是单词或数字的任何内容,得到如下干净的结果:

   Água, 1234
   https://www.example.com/page.html

我能做的最好的就是:

 ^[^\\p{N}\\p{L}]]|[^\\p{N}\\p{L}]$

但这没有用。我看到了很多解决方案,但没有将字符串的开头和结尾与重音字符匹配。

提前致谢。

【问题讨论】:

  • REGEXP [a-zA-Z][0-9] 怎么样
  • 把重音词去掉,如果它们在开头或结尾
  • 嘿,我不知道您为什么删除了您的评论,但它确实有效,谢谢 :)

标签: python regex pyspark


【解决方案1】:

也许,我们可以查看您拥有的数据,然后我们会编写一些类似于:

(?i)\S[a-z].+[a-z0-9]

或者,

(?i)\S*[a-z].+[a-z0-9]

Demo


如果您希望简化/修改/探索表达式,请在regex101.com 的右上角面板中进行说明。如果您愿意,您还可以在this link 中观看它如何与一些示例输入匹配。


测试

import re


regex = r"(?i)\S[a-z].+[a-z0-9]"
string = """
.. -- Água, 1234 ...

 - -- https://www.example.com/page.html *****
"""

print(re.findall(regex, string))

输出

['Água, 1234', 'https://www.example.com/page.html']

【讨论】:

    【解决方案2】:

    我做到了。

    感谢 αԋɱҽԃ αмєяιcαη,这不是最好的解决方案,因为它超出了 pyspark 的 regexp_replace 函数,但它可以工作,只是添加了 re.unicode 标志,并创建了一个 udf。

    
    regexp = re.compile(r'^\W+|\W+$',flags=re.UNICODE)
    
    def remove_non_utf8(string):
        return regexp_2.sub('',regexp_1.sub('',string))
    
    replace_utf8 = udf(remove_non_utf8)
    

    这会从开头或结尾删除所有非 unicode 字符,使用 this url 作为参考。

    --编辑--

    我尝试使用:

    **(?ui)^\W+|\W+$** 
    

    使用pyspark的regexp_replace功能,它不起作用,所以我仍然使用regexp解决方案。

    【讨论】:

      猜你喜欢
      • 2021-07-04
      • 1970-01-01
      • 1970-01-01
      • 2015-09-14
      • 1970-01-01
      • 2018-08-14
      相关资源
      最近更新 更多