我有一个
string = 'long company name with technologies in it'并希望替换所有以
search_string ='techno'带着新的记号
replace_string = 'tech'.我写了一个函数:
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如果我单独执行这些行,它就能工作。但是这个函数本身不起作用。
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'如何在函数中“执行”f-字符串?
发布于 2022-09-24 17:59:02
你把事情搞得太复杂了。只需重新分配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但是,重写类似于以下内容的函数可能更容易一些:
def group_tokens(company_name, string_search, string_replace):
return re.sub(f'\b{string_search}\S*\s*', f'{string_replace} ', company_name, flags=re.UNICODE);发布于 2022-09-24 18:03:39
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'))发布于 2022-09-24 18:08:13
我肯定把事情复杂化了。谢谢:-)
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.nanhttps://stackoverflow.com/questions/73839421
复制相似问题