从字符串中拆分特殊字符组

时间:2013-06-27 16:32:07

标签: python

在test.txt中:

quiet confidence^_^
want:P
(:let's start

代码:

import re
file  = open('test.txt').read()
for line in file.split('\n'):
    line = re.findall(r"[^\w\s$]+|[a-zA-z]+|[^\w\s$]+", line)
    print " ".join(line)

结果显示:

quiet confidence^_^
want : P
(: let ' s start

我尝试将一组特殊字符与字符串分开,但仍然不正确。 有什么建议吗?

预期结果:

quiet confidence ^_^
want :P
(: let's start

1 个答案:

答案 0 :(得分:3)

正如@interjay所说,你必须定义你认为的单词和什么是“特殊字符”。我仍然会使用2个单独的正则表来找出一个单词是什么,什么不是。

word = re.compile("[a-zA-Z\']+")
not_word = re.compile("[^a-zA-Z\']+")

for line in file.split('\n'):
    matched_words = re.findall(word, line)
    non_matching_words = re.findall(not_word, line)
    print " ".join(matched_words)
    print " ".join(non_matching_words)

请注意,空格\s+将被归为非单词。