gpt4 book ai didi

python - Python正则表达式删除空格并在空格所在的位置大写字母?

转载 作者:行者123 更新时间:2023-12-01 05:56:51 25 4
gpt4 key购买 nike

我想从用户提供的单个输入框中创建标签列表,并用逗号分隔,我正在寻找一些表达式来帮助实现此目的。

我想要提供的输入字段和:


删除所有double +空格,制表符,换行(仅保留单个空格)
删除所有(双引号和双引号),逗号除外,逗号只能是
在每个逗号之间,我想要类似“标题大小写”的内容,但不包括第一个单词,根本不包含单个单词,以便在删除最后一个空格时,标记显示为“ somethingLikeTitleCase”或“ something”或“ twoWords” '
最后,删除所有剩余的空间


到目前为止,这是我到目前为止收集的内容:

def no_whitespace(s):
"""Remove all whitespace & newlines. """
return re.sub(r"(?m)\s+", "", s)


# remove spaces, newlines, all whitespace
# http://stackoverflow.com/a/42597/523051

tag_list = ''.join(no_whitespace(tags_input))

# split into a list at comma's

tag_list = tag_list.split(',')

# remove any empty strings (since I currently don't know how to remove double comma's)
# http://stackoverflow.com/questions/3845423/remove-empty-strings-from-a-list-of-strings

tag_list = filter(None, tag_list)


尽管要修改该正则表达式以删除除逗号以外的所有标点符号,我还是迷失了,我什至不知道从哪里开始大写。

有什么想法让我朝正确的方向前进吗?



如建议的那样,这是一些示例输入= required_outputs

形式:“ tHiS is a tAg,'whitespace'!&#^,secondcomment,no!punc $$,ifNOSPACESthenPRESERVEcaps”应显示为
    ['thisIsATag','secondcomment','noPunc','ifNOSPACESthenPRESERVEcaps']

最佳答案

这是解决问题的一种方法(尽管可以使用一个正则表达式,但它没有使用任何正则表达式)。我们将问题分为两个函数:一个函数将字符串拆分为逗号分隔并处理每个片断(parseTags),另一个函数则将字符串处理并将其处理为有效标记(sanitizeTag)。带注释的代码如下:

# This function takes a string with commas separating raw user input, and
# returns a list of valid tags made by sanitizing the strings between the
# commas.
def parseTags(str):
# First, we split the string on commas.
rawTags = str.split(',')

# Then, we sanitize each of the tags. If sanitizing gives us back None,
# then the tag was invalid, so we leave those cases out of our final
# list of tags. We can use None as the predicate because sanitizeTag
# will never return '', which is the only falsy string.
return filter(None, map(sanitizeTag, rawTags))

# This function takes a single proto-tag---the string in between the commas
# that will be turned into a valid tag---and sanitizes it. It either
# returns an alphanumeric string (if the argument can be made into a valid
# tag) or None (if the argument cannot be made into a valid tag; i.e., if
# the argument contains only whitespace and/or punctuation).
def sanitizeTag(str):
# First, we turn non-alphanumeric characters into whitespace. You could
# also use a regular expression here; see below.
str = ''.join(c if c.isalnum() else ' ' for c in str)

# Next, we split the string on spaces, ignoring leading and trailing
# whitespace.
words = str.split()

# There are now three possibilities: there are no words, there was one
# word, or there were multiple words.
numWords = len(words)
if numWords == 0:
# If there were no words, the string contained only spaces (and/or
# punctuation). This can't be made into a valid tag, so we return
# None.
return None
elif numWords == 1:
# If there was only one word, that word is the tag, no
# post-processing required.
return words[0]
else:
# Finally, if there were multiple words, we camel-case the string:
# we lowercase the first word, capitalize the first letter of all
# the other words and lowercase the rest, and finally stick all
# these words together without spaces.
return words[0].lower() + ''.join(w.capitalize() for w in words[1:])


确实,如果运行此代码,我们将得到:

>>> parseTags("tHiS iS a tAg, \t\n!&#^ , secondcomment , no!punc$$, ifNOSPACESthenPRESERVEcaps")
['thisIsATag', 'secondcomment', 'noPunc', 'ifNOSPACESthenPRESERVEcaps']


这段代码中有两点值得澄清。首先是在 str.split()中使用 sanitizeTags。这会将 a b c变成 ['a','b','c'],而 str.split(' ')将产生 ['','a','b','c','']。这几乎肯定是您想要的行为,但是有一个极端的情况。考虑字符串 tAG$$变成一个空格,并被拆分剥离;因此,它变成了 tAG而不是 tag。这可能是您想要的,但如果不是,则必须小心。我要做的是将该行更改为 words = re.split(r'\s+', str),它将在空白处分割字符串,但保留前导和尾随的空字符串;但是,我也将 parseTags更改为使用 rawTags = re.split(r'\s*,\s*', str)。您必须同时进行这两项更改。 'a , b , c'.split(',') becomes ['a ', ' b ', ' c'],这不是您想要的行为,而 r'\s*,\s*'也会删除逗号周围的空格。如果您忽略开头和结尾的空格,则区别并不重要;但是如果不这样做,则需要小心。

最后,不使用正则表达式,而是使用 str = ''.join(c if c.isalnum() else ' ' for c in str)。您可以根据需要将其替换为正则表达式。 (编辑:我在这里消除了一些有关Unicode和正则表达式的错误。)忽略Unicode,您可以将这一行替换为

str = re.sub(r'[^A-Za-z0-9]', ' ', str)


它使用 [^...]匹配除列出的字符外的所有字符:ASCII字母和数字。但是,支持Unicode更好,而且也很容易。最简单的方法是

str = re.sub(r'\W', ' ', str, flags=re.UNICODE)


在这里, \W匹配非单词字符;单词字符是字母,数字或下划线。指定 flags=re.UNICODE(在python 2.7之前不可用;可以将 r'(?u)\W'用于早期版本和2.7),字母和数字都是任何适当的Unicode字符;没有它,它们只是ASCII。如果您不想使用下划线,则可以将 |_添加到正则表达式中以匹配下划线,也可以将它们替换为空格:

str = re.sub(r'\W|_', ' ', str, flags=re.UNICODE)


我相信,这最后一个完全符合我不使用正则表达式的代码的行为。



另外,这就是我如何在没有这些注释的情况下编写相同的代码;这也使我消除了一些临时变量。您可能更喜欢带有变量的代码。这只是一个品味问题。

def parseTags(str):
return filter(None, map(sanitizeTag, str.split(',')))

def sanitizeTag(str):
words = ''.join(c if c.isalnum() else ' ' for c in str).split()
numWords = len(words)
if numWords == 0:
return None
elif numWords == 1:
return words[0]
else:
return words[0].lower() + ''.join(w.capitalize() for w in words[1:])




要处理新希望的行为,我们需要做两件事。首先,我们需要一种方法来固定第一个单词的大写:如果第一个字母的小写字母,则将整个单词都小写;如果第一个字母的大写字母,则将除了第一个字母之外的所有单词都小写。这很容易:我们可以直接进行检查。其次,我们希望将标点符号视为完全不可见:不应将以下单词大写。同样,这很容易-我什至讨论了如何处理上述类似问题。我们只是过滤掉所有非字母数字,非空格字符,而不是将它们转换为空格。整合这些变化使我们

def parseTags(str):
return filter(None, map(sanitizeTag, str.split(',')))

def sanitizeTag(str):
words = filter(lambda c: c.isalnum() or c.isspace(), str).split()
numWords = len(words)
if numWords == 0:
return None
elif numWords == 1:
return words[0]
else:
words0 = words[0].lower() if words[0][0].islower() else words[0].capitalize()
return words0 + ''.join(w.capitalize() for w in words[1:])


运行此代码将为我们提供以下输出

>>> parseTags("tHiS iS a tAg, AnD tHIs, \t\n!&#^ , se@%condcomment$ , No!pUnc$$, ifNOSPACESthenPRESERVEcaps")
['thisIsATag', 'AndThis', 'secondcomment', 'NopUnc', 'ifNOSPACESthenPRESERVEcaps']

关于python - Python正则表达式删除空格并在空格所在的位置大写字母?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12081704/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com