簡體   English   中英

從字符串中拆分特殊字符組

[英]Split group of special characters from string

在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

如@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+將被分組為非單詞。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM