给定一个由英文字符、数字、空格和英文标点符号组成的字符串,长度不超过2000,请将其切分为单词,要求去掉所有的非英文字母,每行输出一个单词。
例如有文本:Python was created in 1990 by Guido van Rossum at Stichting Mathematisch Centrum (CWI, see http://www.cwi.nl) in the Netherlands.
处理完成之后得到以下单词:
Python
was
created
in
by
Guido
van
Rossum
at
Stichting
Mathematisch
Centrum
CWI
see
http
www
cwi
nl
in
the
Netherlands
格式
输入格式
一行字符串
输出格式
若干行,每行一个处理后的单词
样例
输入样例
SyntaxError: cannot assign to literal
输出样例
SyntaxError
cannot
assign
to
literal
基于new BIng的回答:
import re
def split_string(s):
words = re.findall(r'\b[a-zA-Z]+\b', s)
for word in words:
print(word)
s = "This is a test string, with some punctuation! And numbers: 123."
split_string(s)
这段代码使用了正则表达式中的 \b 来匹配单词边界,[a-zA-Z]+ 来匹配一个或多个英文字母。findall 函数会返回所有匹配到的单词,然后我们可以遍历这些单词并输出它们。
不知道你这个问题是否已经解决, 如果还没有解决的话: