python - 一行中的连续资本运行字符串最好在 python 中使用 reduce 或 map 函数

标签 python

这里我试图获取一个句子中所有连续的大写字母字符串。我尝试了以下输出为“LJ”

我一直无法弄清楚为什么它不添加 STRRHLLJ 但它只添加 LJ 而不是列表。它是否假定 [""] 为字符串。

reduce(lambda x ,y : x[-1] + (y) if y.isupper() or y.isspace() else x,"STRR hello HLLJ",[""])

我的输入是: STRR hello HLLJ 我希望得到一个输出 ["STRR","HLLJ"]

测试用例: ABCD AAA lkjl JJJJJJ。这里应该给出 ["ABCD AAA","JJJJJJ"]

感谢任何帮助。

使用 Reduce 我终于想到了这个,但效率不高:

reduce(lambda x, y : x[0:len(x)-1] + [x[-1]+y] 如果 y.isupper() 或 y.isspace() 否则 x + [ ""] if not x[-1].strip() is ""else x,"STRR Hello HLLJ", [""])

最佳答案

在字符串中查找模式是 re module 的内容用于:

In [1]: import re
In [2]: re.findall("[A-Z]+(?: [A-Z]+)*", "ABCD AAA lkjl JJJJJJ")
Out[2]: ['ABCD AAA', 'JJJJJJ']

或者,如果您不想包含属于另一个词的大写字母,您可以使用 word boundary anchors 排除它们。 :

In [3]: re.findall(r"\b[A-Z]+(?: [A-Z]+)*\b", "ABCD AAA Lkjl JJJJJJ")
Out[3]: ['ABCD AAA', 'JJJJJJ']

警告:这只查找 ASCII 字母。

关于python - 一行中的连续资本运行字符串最好在 python 中使用 reduce 或 map 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33412629/

相关文章:

python - 如何唯一地组合2个列表

python - 使用 3 个组件创建 numpy 向量

python - s3fs 突然停止在 Google Colab 中工作,错误为 "AttributeError: module ' aiobotocore' 没有属性 'AioSession'”

python - PyTorch张量高级索引

python - IRC Python 机器人 : Best Way

python - Tornado :来自迭代器的 AsyncHttpClient.fetch?

python - 如何使用 requests.get() 仅获取 <body> 标记内的文本?

python - Azure Functions IP 地址超出范围

python - pip 错误 "No matching distribution found for perceptilabs"

python - 如何在python中构建动态sql查询并使用executemany()插入?