我有點努力解決以下案例......
想象一下這個字串:
str = "three hundred four - fifty six * eight"
有沒有辦法獲得以下陣列:
array = ["three hundred", " ", "four", "-", "fifty six", "*", "eight"]
知道我有多個運算子的串列(我猜用作字串中的分隔符)?
在空格分隔符上拆分字串很容易,但我想將每個分隔的部分保留為我的串列中的一個專案!
另外,這是否可能不使用任何匯入,例如 re ?
提前致謝 !
uj5u.com熱心網友回復:
假設您只需要單詞,您可以使用簡單的正則運算式完成此操作
import re
s = "three hundred four - fifty six * eight"
print(re.findall(r"\w ",s))
結果:
['three', 'hundred', 'four', 'fifty', 'six', 'eight']
uj5u.com熱心網友回復:
以更演算法的方式:
def split(string_sep, separators):
res = []
last = 0 # the last position of an separators
index = 0
for index, char in enumerate(string_sep):
if char in operators:
res.append(string_sep[last:index].strip()) # strip if you dont want space enter separtors and words
res.append(char)
last = index 1 # 1 to not take the separator
# for the last add to the list
if last <= index:
res.append(string_sep[last:])
return res
uj5u.com熱心網友回復:
這是一個可以使用該字串執行您想要的操作的函式。然而,問題更多地在于如何處理格式不正確的字串。Chris 在答案中的評論指出了一個問題,該問題討論了使用抽象語法樹進行標記的問題,這正是您真正需要的。本質上,這有點像從頭開始撰寫 re 模塊。反正:
def deconstructor(sample, delims):
result = []
loader = []
for item in sample:
if item not in delims:
loader.append(item)
else:
result.append(''.join(loader).strip())
loader.clear()
result.append(item) #add that delimiter to list
if loader: #if not required for properly formatted string
result.append(''.join(loader).strip())
return result
>>> deconstructor("three hundred four - fifty six * eight", (' ', '-', '*', '/'))
>>> ['three hundred', ' ', 'four', '-', 'fifty six', '*', 'eight']
uj5u.com熱心網友回復:
不使用進口:
mstr = "three foo fifty bar four foo - fifty six * eight"
dels = ['-', '*', ' ', '/']
# find delimeters
split_at = [0]
for item in dels:
indices = [i for i, x in enumerate(mstr) if x == item]
for index in indices:
split_at.append(index)
split_at = sorted(split_at)
# split at delimeters
split_str = []
split_str.append(mstr[:split_at[1]])
for split_id in range(2, len(split_at)):
split_str.append(mstr[split_at[split_id-1]])
split_str.append(mstr[split_at[split_id-1] 1:split_at[split_id]])
split_str.append(mstr[split_at[-1]])
split_str.append(mstr[split_at[-1] 1 :])
結果:
['three foo fifty bar ', ' ', ' four foo ', '-', ' fifty six ', '*', ' eight']
uj5u.com熱心網友回復:
我們可以借助正則運算式拆分字串。這里我們只需要創建一個正則運算式,就可以減少代碼行數。
# Python3 code to demonstrate working of
# Splitting operators in String
# Using re.split()
import re
# initializing string
test_str = "three hundred four - fifty six * eight"
# printing original string
print("The original string is : " str(test_str))
# Using re.split()
# Splitting operators in String
res = re.split(r'(\ |\-|\*|\/)', test_str)
# printing result
print("The list after performing split functionality : " str(res))
要了解我們如何創建正則運算式,您可以從此鏈接獲取幫助https://www.programiz.com/python-programming/regex
我只為想要在re模塊的幫助下拆分字串的人發布此答案Python。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/367592.html
