-1

在 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
4

1 回答 1

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+将被分组为非单词。

于 2013-06-27T17:10:05.903 回答