Python 3
text = "(CNN)Meaalofa Te'o -- Buemi. Canberra,"
def discard_punctuation(text):
regex = '\W*^\s^\d*-'
return re.sub(regex, "", text)
def handle_text(text):
text_without_punctuation = discard_punctuation(text)
words_array = text_without_punctuation.split()
pass // Breakpoint
handle_text(text)
从任意文本我只想选择单词。调查这个问题时,我发现有时单词里面有连字符。或者一个数字也可以(9岁,像峡谷一样)
我的正则表达式是regex='\W*^\s^\d*-'
取所有非字母数字字符;排除split方法所必需的所有空格字符;排除所有后面没有连字符的数字
我还应该排除单词中没有的连字符
结果是: :['(CNN)Meaalofa','Te'o','--','Buemi','Canberra']
文档:https://docs.python.org/3/howto/regex.html
\W
Matches any non-alphanumeric character; this is equivalent to the class [^a-zA-Z0-9_].
我认为点、逗号、连字符、方括号和撇号应该匹配\W
问题: 1.我不明白为什么:括号、点、逗号和撇号仍然存在。
我想说我排除了撇号。我需要它,它在结果中是存在的,它是好的。但我搞不懂那是怎么发生的你能帮我理解撇号是怎么出现在结果中的吗。
嗯,“--”在这里绝对是个错误。如何应对?
你能给我推荐一个更好的regexp吗
你对一个“词”的定义相当模糊,你可以得出:
参见a demo on ideone.com和regex101.com。你可以重新定义“单词”是什么
相关问题 更多 >
编程相关推荐