[英]Regular expression in Python to split a string based on characters that begin with @ and end with :?
我有看起来像这样的字符串:
sentences = "@en:The dog went for a walk@es:El perro fue de paseo"
所需的 output:
splitted = ['The dog went for a walk', 'El perro fue de paseo']
当前代码:
splitted = re.split("^@:$", sentences)
因此,id 喜欢根据以添加符号@开头并以冒号:结尾的字符来拆分句子,因为这些是所有语言的编码方式,例如 (@en:, @es:, @fr:, @nl : ETC。)
您可以使用否定字符 class 从 @ 拆分为:而不匹配任何这些字符。
结果中可能有空条目,您可以将其过滤掉。
@[^@:]*:
import re
sentences = "@en:The dog went for a walk@es:El perro fue de paseo"
splitted = [s for s in re.split("@[^@:]*:", sentences) if s]
print(splitted)
Output
['The dog went for a walk', 'El perro fue de paseo']
你好试试这个代码它会帮助你
import re
sentences = "@en:The dog went for a walk@es:El perro fue de paseo"
splitted = re.split(r"@[a-zA-z]+:",sentences)
print(splitted)
你需要这个正则表达式: @[^@:]+:
首先, @
匹配一个@
接下来, [^@:]+
匹配任意数量的字符(最少一个)不是@
或:
最后, :
匹配一个:
import re
sentences = "@en:The dog went for a walk@es:El perro fue de paseo"
splitted = re.split("@[^@:]+:", sentences)
print(splitted[1:])
output:
['The dog went for a walk', 'El perro fue de paseo']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.