更新:我简化了这个问题(最初的任务是句子拆分)。 以下代码应将每个字符"."定义为定界符,但应为每个字符FALSE输出:
import re
delimiters = ['!', '?', '.']
def is_delimiter(char):
number = str(re.findall("\d+\.\d+", text))
if char in delimiters and char not in number:
return True
return False
text = "Hello. I'll come back on 12.09."
for char in text:
print(char, is_delimiter(char))
在将"Hello"定义为定界符并输出TRUE之后,我需要给"."字符。 "12.09"中的字符(假设12.09是一个数字)将被定义为NOT分隔符,并输出FALSE。
所以我有:
o False
n False
False
1 False
2 False
. False
0 False
9 False
. False
我要拥有的东西:
o False
n False
False
1 False
2 False
. False
0 False
9 False
. True
谢谢!
分析解答
您实际上只需要检查定界符后面的字符是否为空格即可判断它是否不在句子的末尾。不需要。
delimiters = ['!', '?', '.']
def is_delimiter(char, next_char):
if char in delimiters:
if next_char is not None:
if next_char == ' ':
return True
else:
return True
return False
text = "Hello. I'll come back on 12.09."
for i in range(0, len(text)):
char = text[i]
j = i+1
if j < len(text):
next_char = text[j]
else:
next_char = None
print(char, is_delimiter(char, next_char))