【问题标题】:Using re to sanitize a word file, allowing letters with hyphens and apostrophes使用 re 清理 word 文件,允许带有连字符和撇号的字母
【发布时间】:2016-09-22 13:55:32
【问题描述】:

这是我目前所拥有的:

import re

def read_file(file):
    words = []
    for line in file:
        for word in line.split():
            words.append(re.sub("[^a-z]", "", word.lower()))

就目前而言,这会将“can't”读作“cant”,将“co-ordinate”读作“coordinate”。我想读单词,以便允许这两个标点符号。如何修改我的代码来做到这一点?

【问题讨论】:

  • 试试这个re.sub(r"[^a-z\-']", "", word.lower())
  • @ritesht93 如果将连字符放在开头或结尾,则无需转义。

标签: python regex list file sanitization


【解决方案1】:

可以有两种方法:一种是 ritesht93 在对问题的评论中建议的,尽管我会使用

words.append(re.sub("[^-'a-z]+", "", word.lower()))
                       ^^    ^ - One or more occurrences to remove in one go
                        | - Apostrophe and hyphen added

+ 量词将一次性删除与模式匹配的不需要的字符。

请注意,连字符添加在否定字符类的开头,因此不必转义。 注意:如果其他不太精通正则表达式的开发人员稍后要维护它,仍然建议将其转义

如果您有 Unicode 字母,第二种方法会很有帮助。

ur'((?![-'])[\W\d_])+'

查看regex demo(使用re.UNICODE 标志编译)

该模式匹配任何非字母(除了由于负前瞻(?![-'])而导致的连字符或撇号)、任何数字或下划线 ([\W\d_])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-07
    • 1970-01-01
    • 2015-03-19
    • 1970-01-01
    • 2016-09-23
    • 2018-07-15
    相关资源
    最近更新 更多