【发布时间】:2021-01-28 16:35:22
【问题描述】:
我对分词有一些问题,任务是将一个句子分成单词。
这就是我目前所做的。
def tokenize(s):
d = []
start = 0
while start < len(s):
while start < len(s) and s[start].isspace():
start = start+1
end = start
while end < len(s) and not s[end].isspace():
end = end+1
d = d + [s[start:end]]
start = end
print(d)
运行程序:
>>> tokenize("He was walking, it was fun")
['He', 'was', 'walking,', 'it', 'was', 'fun']
这很好用,但问题是如您所见,我的程序将在单词 walk 中包含逗号。我想将逗号(和其他“符号”)分隔为一个单独的“单词”。
如:
['He', 'was', 'walking', ',', 'it', 'was', 'fun']
如何修改我的代码来解决这个问题?
提前致谢!
【问题讨论】:
-
如果你的目标是将一个句子拆分成单词,并且非字母字符将是他们自己的单词,那么解析像
From 1969-2009, David Peters-Foster woke up between 9:15AM and 10:15AM to go for a jog around the cul-de-sac with his neighbor's husband.这样的句子输出将是一团糟 -
你可以在这些情况下使用正则表达式,比如
import re然后print(re.findall(r'[^\W_]+|[^\w\s]|_', text))