如何使用正则表达式缩写所有以大写字母开头的单词
How can I use Regex to abbreviate words that all start with a capital letter
我想通过编写 python 脚本来缩写字符串中的单词。
例如,我在沙特阿拉伯首都利雅得的沙特国王大学学习;成为我在SA首都利雅得的KSU学习。
我尝试使用 lambda 来扫描所有字符串,但在找到它后我无法删除剩余的单词。
import re
str = "I studied in King Saud University, which is in Riyadh, the capital of Saudi Arabia"
result = re.sub(r"\b[A-Z]", lambda x: x.group() ,str)
print(result)
您需要实际消耗两个或更多以大写字母开头的单词。
你可以使用像
这样的东西
result = re.sub(r"\b[A-Z]\w*(?:\s+[A-Z]\w*)+", lambda x: "".join(c[0] for c in x.group().split()), text)
参见 Python demo:
import re
text = "I studied in King Saud University, which is in Riyadh, the capital of Saudi Arabia"
result = re.sub(r"\b[A-Z]\w*(?:\s+[A-Z]\w*)+", lambda x: "".join(c[0] for c in x.group().split()), text)
print(result)
# => I studied in KSU, which is in Riyadh, the capital of SA
见regex demo。 详情:
\b
- 单词边界
[A-Z]
- 大写 ASCII 字母
\w*
- 零个或多个单词字符
(?:\s+[A-Z]\w*)+
- 出现一次或多次
\s+
- 一个或多个空格
[A-Z]\w*
- 一个大写 ASCII 字母,然后是零个或多个单词字符。
"".join(c[0] for c in x.group().split())
部分从匹配值中的 non-whitespace 块中获取第一个字符,并将它们连接成一个字符串。
为了支持所有 Unicode 大写字母,我建议使用 PyPi 正则表达式模块,并使用
import regex
#...
result = regex.sub(r"\b\p{Lu}\p{L}*(?:\s+\p{Lu}\p{L}*)+", lambda x: "".join(c[0] for c in x.group().split()), text)
其中 \p{Lu}
匹配任何 Unicode 大写字母,\p{L}
匹配任何 Unicode 字母。
这是一个有效的解决方案。我删除了 lambda 函数并替换了每个出现的大写字母 K、S、U,每个字母后跟小写字母和 space.
import re
str = "I studied in King Saud University, which is in Riyadh, the capital of Saudi Arabia"
find = re.compile(r"[K][a-z]+\s[S][a-z]+\s[U][a-z]+")
substitute = "KSU"
print(find.sub(substitute,str))
我想通过编写 python 脚本来缩写字符串中的单词。 例如,我在沙特阿拉伯首都利雅得的沙特国王大学学习;成为我在SA首都利雅得的KSU学习。
我尝试使用 lambda 来扫描所有字符串,但在找到它后我无法删除剩余的单词。
import re
str = "I studied in King Saud University, which is in Riyadh, the capital of Saudi Arabia"
result = re.sub(r"\b[A-Z]", lambda x: x.group() ,str)
print(result)
您需要实际消耗两个或更多以大写字母开头的单词。
你可以使用像
这样的东西result = re.sub(r"\b[A-Z]\w*(?:\s+[A-Z]\w*)+", lambda x: "".join(c[0] for c in x.group().split()), text)
参见 Python demo:
import re
text = "I studied in King Saud University, which is in Riyadh, the capital of Saudi Arabia"
result = re.sub(r"\b[A-Z]\w*(?:\s+[A-Z]\w*)+", lambda x: "".join(c[0] for c in x.group().split()), text)
print(result)
# => I studied in KSU, which is in Riyadh, the capital of SA
见regex demo。 详情:
\b
- 单词边界[A-Z]
- 大写 ASCII 字母\w*
- 零个或多个单词字符(?:\s+[A-Z]\w*)+
- 出现一次或多次\s+
- 一个或多个空格[A-Z]\w*
- 一个大写 ASCII 字母,然后是零个或多个单词字符。
"".join(c[0] for c in x.group().split())
部分从匹配值中的 non-whitespace 块中获取第一个字符,并将它们连接成一个字符串。
为了支持所有 Unicode 大写字母,我建议使用 PyPi 正则表达式模块,并使用
import regex
#...
result = regex.sub(r"\b\p{Lu}\p{L}*(?:\s+\p{Lu}\p{L}*)+", lambda x: "".join(c[0] for c in x.group().split()), text)
其中 \p{Lu}
匹配任何 Unicode 大写字母,\p{L}
匹配任何 Unicode 字母。
这是一个有效的解决方案。我删除了 lambda 函数并替换了每个出现的大写字母 K、S、U,每个字母后跟小写字母和 space.
import re
str = "I studied in King Saud University, which is in Riyadh, the capital of Saudi Arabia"
find = re.compile(r"[K][a-z]+\s[S][a-z]+\s[U][a-z]+")
substitute = "KSU"
print(find.sub(substitute,str))