我正在尝试在 python 中拆分多个字符的字符串,就像我在 Java 中所做的那样:
private static final String SPECIAL_CHARACTERS_REGEX = "[ :;'?=()!\\[\\]-]+|(?<=\\d)(?=\\D)";
String rawMessage = "let's meet tomorrow at 9:30p? 7-8pm? i=you go (no Go!) [to do !]";
String[] tokens = rawMessage.split(SPECIAL_CHARACTERS_REGEX);
System.out.println(Arrays.toString(tokens));
这是具有正确输出的工作演示:Working Demo
我试图在 python 中做完全相同的事情,但是当我这样做时,如果我只是在正则表达式中添加“单引号”字符,它根本不会标记化。如何从 Python 中创建与上述 Java 程序相同的解析结果?
这个:
import re
tokens = re.split(' \.', line);
print tokens
对于行:
"let's meet tomorrow at 9:30p? 7-8pm? i=you go (no Go!) [to do !]"
给予:
["let's meet tomorrow at 9:30p? 7-8pm? i=you go (no Go!) [to do !]";]
当我这样做的时候:
[let, s, meet, tomorrow, at, 9, 30, p, 7, 8, pm, i, you, go, no, Go, to, do]
最佳答案
使用您在 Java 中使用的相同正则表达式:
line = "let's meet tomorrow at 9:30p? 7-8pm? i=you go (no Go!) [to do !]"
tokens = re.split("[ :;'?=()!\\[\\]-]+|(?<=\\d)(?=\\D)", line)
tokens = [token for token in tokens if len(token) != 0] # remove empty strings!
print(tokens)
# ['let', 's', 'meet', 'tomorrow', 'at', '9', '30p', '7', '8pm', 'i', 'you', 'go', 'no', 'Go', 'to', 'do']
关于python - 在python中拆分多个字符的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22753371/