def extract_words(string):
is_word = False # 用来标记是否正在读取单词
start_index = 0 # 用来记录单词开始的位置
lst = [] # 用来存放单词
for index, char in enumerate(string):
if char.isalnum(): # 如果是字母或数字,则标记为正在读取单词
if not is_word: # 如果是单词的开始
is_word = True
start_index = index
elif is_word: # 如果当前字符不是字母或数字,且之前正在读取单词
lst.append(string[start_index:index]) # 将单词添加到列表中
is_word = False # 标记为不再读取单词
# 处理字符串末尾的单词(如果有的话)
if is_word:
lst.append(string[start_index:])
return lst
if __name__ == '__main__':
string = "the sky is blue"
words = extract_words(string)
print(words)
提取单词 python
最新推荐文章于 2024-08-06 17:45:33 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)