例如:如何在Python中將字符串分割爲多個單詞,空格和製表符?
String1='Hi what are you doing?'
應拆分等:
List1=['Hi','\s','what','\s','are','\s','you','\s','doing','\s','?']
例如:如何在Python中將字符串分割爲多個單詞,空格和製表符?
String1='Hi what are you doing?'
應拆分等:
List1=['Hi','\s','what','\s','are','\s','you','\s','doing','\s','?']
import re
s = your string here \nhello" re.split('\s+', s)
通過re模塊的另一種方法。
>>> import re
>>> s = "your string here \nhello \thi"
>>> re.findall(r'\S+', s) ['your', 'string', 'word', 'hello', 'hi']
這將匹配一個或多個非空格字符。
試試這個:
s ='Hi what are you doing?'
import re
re.findall('[a-zA-Z]{1,}|[^a-zA-Z]{1,}', s)
輸出:
['Hi', ' ', 'what', ' ', 'are', ' ', 'you', ' ', 'doing', '?']
如果你想只拆分:
String1='Hi what are you doing ?'
print(String1.split())
輸出:
['Hi', 'what', 'are', 'you', 'doing', '?']
如果你想爲你的例子所示
:
print(String1.replace(" "," \s ").split())
輸出:
['Hi', '\\s', 'what', '\\s', 'are', '\\s', 'you', '\\s', 'doing', '\\s', '?']
你嘗試過這麼遠嗎? – favoretti
您應該閱讀https://docs.python.org/3.6/library/stdtypes.html#str.split – luxcem
我認爲這裏的想法是他想要包括所有空格以及從標點符號中拆分詞。 –