Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/332.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/csharp-4.0/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何进行python单词替换?_Python_Regex_String_Replace - Fatal编程技术网

如何进行python单词替换?

如何进行python单词替换?,python,regex,string,replace,Python,Regex,String,Replace,我想替换字符串中的一些单词。例如,“eq”到“=”,“gt”到“>” 例如: s = "name eq 'alex' and age gt 36" to "name = 'alex' and age > 36" 我不能使用string.replace(),因为它会替换字符。 我是否应该将句子拆分,然后re.sub(r'^eq$,'=',s)?有没有一个简单的方法可以做到这一点 另外,我不想做s.replace('eq','='),因为字符串的开头或结尾可能有单词。例如,在sender e

我想替换字符串中的一些单词。例如,“eq”到“=”,“gt”到“>”

例如:

s = "name eq 'alex' and age gt 36" to "name = 'alex' and age > 36"
我不能使用string.replace(),因为它会替换字符。 我是否应该将句子拆分,然后
re.sub(r'^eq$,'=',s)
?有没有一个简单的方法可以做到这一点


另外,我不想做
s.replace('eq','=')
,因为字符串的开头或结尾可能有单词。例如,在
sender eq me
中将我替换为'alex'应该会导致
sender='alex'

似乎
replace
是完美的解决方案

s = "name eq 'alex' and age > 36" 
goal = "name = 'alex' and age > 36"
s = s.replace(" eq ", " = ")

s == goal

这里我们使用
REGEX
来实现所需的输出


Regex:
(?:(?使用Regex替换。它将避免误导性影响

import re

s = ("name eq 'alex' and age > 36 equity eq\n"
    "{ dictionary: \"\" } eq { dictionary: \"\" }\n"
    "\"string\" eq \"string\"\n"
    "var eq var\n"
    "[\"list\"] eq [\"list\"]\n"
    "(\"tuple\") eq (\"tuple\")")

regex_template_start = r"(?<=[' \"\w\[\]\(\)\{\}])\b"
regex_template_end   = r"\b(?=[' \"\w\[\]\(\)\{\}])"

s = re.sub(r"{0}{1}{2}".format(regex_template_start, "eq", regex_template_end), '=', s)
s = re.sub(r"{0}{1}{2}".format(regex_template_start, "gt", regex_template_end), '>', s)

print(s)
重新导入
s=(“姓名eq‘alex’和年龄>36岁权益eq\n”
{字典:\“\”}eq{字典:\“\”}\n
“\'string\'eq\'string\'n”
“var-eq-var\n”
“[\”列表\“]eq[\”列表\“]\n”
“(\'tuple\”)eq(\'tuple\”)

regex_template_start=r“(?您可以使用一个简单的for循环来避免更改'eq'和'gt'的其他实例

# split on space character
words = s.split(' ')    

# loop and check every word
for i, w in enumerate(words):    

    # replace occurrence of r'^eq$'
    if w == 'eq':    
        words[i] = '='

    # replace occurrence of r'^gt$'
    elif w == 'gt':     
        words[i] = '>'

s = ' '.join(words)

只需使用re.sub功能即可

import re
s = "name eq 'alex' with equity gt 36"
s = re.sub(r'\s{1}eq\s{1}', ' = ', s)
s = re.sub(r'\s{1}gt\s{1}', ' > ', s)
print(s)

输出为name='alex'with equity>36正是您想要的

一个解决方案是创建一个字典,其中包含需要替换的所有值的
key:value
。 将字符串拆分为一个列表可以解决以下单词的问题 equity 我已经尝试过替换字典中列表中的单词。它并不完美,但可以用另一种方法来完成这项任务。我正在尝试更新它

s = "name eq 'alex' and age gt 36"
[s.replace(char, dicta.get(char)) for char in s.split(" ") if char in dicta ]

“无法使用string.replace(),因为它将替换为字符”我不太清楚您不想使用string.replace()的原因。这似乎是你想要实现的完美解决方案。他可能是说他不想让
eq
gt
lt
这样的东西变成
=uity
,如果
eq
gt
lt
用单独的词表达,那么使用
字符串就没有问题了。替换
@bulbus,OP说“我不想做s.replace('eq','='),因为字符串的开头或结尾可能有单词“我假设这意味着它不总是以空格分隔的。预期的输出是
a eq b
eqe=b
'a'=b
(a)=b
,你能解释一下吗?@Mengo lookup“lookup”lookarounds“!@bulbus我可能会选择
(?我想你可以在聊天部分讨论这个问题,评论不是一个好方法。在评论中,OP说为什么这个方法不是我们想要的,因为它可以修改其他的“eg”或“gt”实例,比如@flakesI指出的“equity”中的“equity”,我也不知道否决这个优雅解决方案的原因是什么!似乎是b比其他解决方案更好。在链的末尾
。替换(“lt”,“<”)
是可以添加的。@SanyamMehra继续,所以我们应该添加答案,这将有助于所有有这种模式问题的人,而不是仅仅看一个具体的案例。@SanyamMehra当一件事情可以用内置函数优雅地完成时,为什么我们要用
正则表达式
这是我的观点由您决定:)请参考问题:“ps.我不想做s.replace('eq','='),因为字符串的开头或结尾可能有单词。”您的建议不符合OP的要求。请删除行之间不必要的空格。如果运算符也可以位于字符串的边缘,则可以显式检查开始和结束,而不是对整个字符串进行操作。 equity
dicta = {
    "eq" : "=",
    "gt" : ">",
    "lt" : "<"
}
s = "name eq 'alex' and age gt 36"
[s.replace(char, dicta.get(char)) for char in s.split(" ") if char in dicta ]