我正在將一些 Matlab 代碼移植到 Python。在此代碼中,有許多以許多不同方式切片的大型矩陣實體,例如M(2:45,13:18)、M(:12,:)、V(4)、V(:27)等。在技術上可以手動將其轉換為 numpy 表示法,方法是用方括號替換括號并將所有索引減 1 (之后除外:)但它非常乏味,并且很有可能我會在某些時候打錯字。
我嘗試將其自動化,但我的 grep/awk/決議技能還不夠好。是否有腳本可以完成這項作業?
uj5u.com熱心網友回復:
假設你有你的 matlab 代碼在一個字串中,你可以用 Python 格式化它。您可以使用正則運算式匹配替換來做到這一點:
import re
def format_indexers(match):
# Format any "(x:y:z)" into python format
ret = match[0].replace("(", "[").replace(")", "]") # replace brackets
ret = re.sub(r"(\d ):", lambda x: str(int(x[1]) - 1) ":", ret) # replaces numbers by decremented ones
return ret
s = "M(2:45,13:18), M(:12,:), V(4), V(:27)"
# Searches expressions between parenthesis and apply format_indexers to found matches
re.sub(r"\(.*\)", format_indexers, s)
輸出:
'M[1:45,12:18], M[:12,:], V[3], V[:27]'
uj5u.com熱心網友回復:
這是基于 PlainRavioli 的原始答案的另一個觀點:
INPUT = 'M(2:45,13:18) M(:12,:) V(4) V(:27)'
import re
def my_replace(m):
m = m.group()
a, m = m[0], m[2:-1]
m = m.split(',')
for k in range(len(m)):
if ':' in m[k]:
m[k] = m[k].split(':')
if m[k][0]:
m[k][0] = str(int(m[k][0])-1)
m[k] = ':'.join(m[k])
else:
m[k] = str(int(m[k])-1)
m = ','.join(m)
m = a '[' m ']'
return m
OUT = re.sub('\\w\\(\d*:?\d*(,\d*:?\d*)?\\)', my_replace, INPUT)
print(OUT)
# yields: M[1:45,12:18] M[:12,:] V[3] V[:27]
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/511862.html
