[英]Execute f-string in function
我有一個
string = 'long company name with technologies in it'
並想要替換所有以
search_string ='techno'
帶有新令牌
replace_string = 'tech'.
我寫了一個function:
def group_tokens(company_name, string_search, string_replace):
try:
x = company_name.split(" ")
print(f"x = [re.sub('^{string_search}.*', '{string_replace}', i) for i in x]")
exec(f"x = [re.sub('^{string_search}.*', '{string_replace}', i) for i in x]")
x = " ".join(x)
x = " ".join(re.split("\s+", x, flags=re.UNICODE))
return(x)
except:
return np.nan
如果我單獨執行這些行,它就可以工作。 但是 function 本身不起作用。
group_tokens('long company name with technologies in it', 'techno', 'tech') = 'long company name with technologies in it'
我期待
group_tokens('long company name with technologies in it', 'techno', 'tech') = 'long company name with tech in it'
如何在 function 中“執行”f-string?
你把這個復雜化了。 只需重新分配 x:
def group_tokens(company_name, string_search, string_replace):
try:
x = company_name.split(" ")
x = [re.sub(f'^{string_search}.*', string_replace, i) for i in x])
x = " ".join(x)
x = " ".join(re.split("\s+", x, flags=re.UNICODE))
return x
except:
return np.nan
但是重寫 function 可能更容易,類似於以下內容:
def group_tokens(company_name, string_search, string_replace):
return re.sub(f'^{string_search}\S*\s*', f'{string_replace} ', company_name);
def replace(string,x,y):
words = string.split(' ')
string = ''
while words:
word = words.pop(0)
if word.startswith(x):
word = y
string+=word+' '
return string[:-1]
print(replace('long company name with technologies in it', 'techno', 'tech'))
我肯定把它復雜化了。 謝謝:-)
def group_tokens(company_name, string_search, string_replace):
try:
x = company_name.split(" ")
x = [re.sub(f'^{string_search}.*', string_replace, i) for i in x])
x = " ".join(x)
x = " ".join(re.split("\s+", x, flags=re.UNICODE))
return x
except:
return np.nan
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.