【问题标题】:replacing special characters in string Python替换字符串Python中的特殊字符
【发布时间】:2022-01-22 21:15:41
【问题描述】:

我正在尝试将数据框中的特殊字符替换为非重音字符或其他字符。

我可以用一个替换

df['col_name'] = df.col_name.str.replace('?','j') 

这变成了“?”到 'j' - 但是 - 我似乎无法弄清楚如何更改多个..

我有一个想要更改的特殊字符列表。我试过用字典,但它似乎不起作用

the_reps = {'?','j'}

df1 = df.replace(the_reps, regex = True)

这给了我在位置 0 处没有可替换的错误

编辑:

这是有效的——虽然它可能不是那么漂亮:

df[col]=df.col.str.replace('old char','new char')
df[col]=df.col.str.replace('old char','new char')
df[col]=df.col.str.replace('old char','new char')
df[col]=df.col.str.replace('old char','new char')...

每一个..

【问题讨论】:

  • 试试df['column'] = df['column'].str.replace('.*@+.*', 'replacement')。我发现:stackoverflow.com/questions/34702338/…
  • 这能回答你的问题吗? Replace Multiple Values of columns
  • 我认为我遇到的问题是 - 我想用特定的替换字符替换某些字符 - 而不仅仅是所有字符都具有相同或空格或其他内容。
  • 你能查一下this answer@PorscheAdams
  • 我仍然在位置 0 得到错误,没有可替换的内容 -

标签: python replace


【解决方案1】:

您可以将Series.replace 与字典一起使用

#d = { 'actual character ':'replacement ',...}

df.columns = df.columns.to_series().replace(d, regex=True)

【讨论】:

  • 给了我一个错误:在位置 0 没有可替换的东西 -
【解决方案2】:
import re
s=re.sub("[_list of special characters_]","",_your string goes here_)
print(s)

这个例子..

str="Hello$@& Python3$"
import re
s=re.sub("[$@&]","",str)
print (s)
#Output:Hello Python3

解释在这里..

s=re.sub("[$@&]","",s)
  • 要替换的模式 → “[$@&]”
  • [] 用来表示一组字符
  • [$@&] → 将匹配 $ 或 @ 或 &
  • 替换字符串以空字符串形式给出
  • 如果在字符串中找到这些字符,它们将被替换为空字符串

【讨论】:

    【解决方案3】:

    试试这个:

    import re
    my_str = "hello Fayzan-Bhatti Ho~!w"
    my_new_string = re.sub('[^a-zA-Z0-9 \n\.]', '', my_str)
    print my_new_string
    

    输出: hello FayzanBhatti How

    【讨论】:

    • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
    • 我正在尝试用特定字符替换特殊字符 - 而不仅仅是删除它们 - 所以更像:这是 ?ust gra$$ - to - 这只是草
    猜你喜欢
    • 1970-01-01
    • 2014-07-22
    • 2014-12-07
    • 1970-01-01
    相关资源
    最近更新 更多