簡體   English   中英

python中基於特殊字符的拆分字符串

[英]split string based on special characters in python

例如,字符串是hello %$ world %^& let me ^@ love && you預期結果將是一個變量中的 hello 而其他變量中的其余部分例如 a="hello" b="world" 等。

使用正則表達式

像這樣:-

import re
a = "hello %$ world %^& let me ^@ love && you"
print(re.findall(r'\w+',a))

您可以使用(從字符串中檢索世界的正則表達式):

import re
my_string = "hello %$ world %^& let me ^@ love && you"
re.findall(r'\w+\b', my_string)
# ['hello', 'world', 'let', 'me', 'love', 'you']

請在正則表達式 HOWTO 中查看有關正則表達式的更多信息

更新

如評論中所問,附加正則表達式以檢索由特殊字符分隔的單詞組:

my_string = "hello world #$$ i love you #$@^ welcome to world"
re.findall(r'(\w+[\s\w]*)\b', my_string)  
# ['hello world', 'i love you', 'welcome to world']

基本答案是正則表達式。 我建議您查看 NLTK 的標記器,它們包含對該主題的研究,並讓您可以靈活地稍后切換到更復雜的內容。 你猜怎么着? 它也提供了一個基於正則表達式的標記器!

from nltk.tokenize import RegexpTokenizer 

tokenizer = RegexpTokenizer(r'([A-Za-z0-9 ]+)')
corpus = tokenizer.tokenize("hello %$ world %^& let me ^@ love && you")

暫無
暫無

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

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