我可以在python中的一个语句中进行多个字符串替换吗 [英] Can I do a number of string replace in one statement in python

查看:46
本文介绍了我可以在python中的一个语句中进行多个字符串替换吗的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用以下语句在我的字符串中减少一些垃圾字符:

I am trying to few junk characters in my string using the following statement:

desc = string.replace(desc,'“','"')
desc = string.replace(desc,'”','"')
desc = string.replace(desc,'·','.') 

我可以将以上 3 个语句写成一个语句还是将第一个两个语句写成一个语句.

Can I write the above 3 statements in to a single statement or atlease the 1st two statements to a single statement.

我不能在我的项目中使用任何第三方库.

I can not use any third-party libraries in my project.

编辑@unutbu:
我的字符串如下所示:

Edit @unutbu:
My String looks like below:

这是'“'我的测试字符串”". 我想用适当的 HTML 替换 unicode,而不是仅用 unicode 值替换整个字符串.

This is '“' my teststring '”'. I want to replace unicode with appropriate HTML not the whole string only with unicode values.

使用代码后:

import HTMLParser

text='“ ” ·'
parser=HTMLParser.HTMLParser()
desc=parser.unescape(text)

我只得到 HTML 等价物,而不是字符串.但我只想替换适当的值,保留原始字符串中的所有内容.

I am getting only the HTML equivalents , not the string. But I just want to replace the appropriate values keeping everything in Original String.

我希望输出如下:

这是我的测试字符串".我想用适当的 HTML 替换 unicode,而不是只用 unicode 值替换整个字符串.

This is "my teststring". I want to replace unicode with appropriate HTML not the whole string only with unicode values.

推荐答案

HTMLParser 在标准库中:

import HTMLParser

text='“ ” ·'
parser=HTMLParser.HTMLParser()
desc=parser.unescape(text)
print(desc)
# " " ·

如果你想在一个单一的语句中,你当然可以这样做

If you want that in a single statement, you could of course do

desc=HTMLParser.HTMLParser().unescape(text)

但如果您需要在多个地方调用 unescape,这可能不是一个优势,而且一般来说,像这样链接调用会使识别异常发生的位置变得更加困难.

but that might not be an advantage if you need to call unescape in more than one place, and in general, chaining calls like this makes it harder to identify where exceptions occur.

请注意,HTMLParser.unescape 将取消转义 htmlentitydefs.names2codepoint 中定义的所有 HTML 实体(加上 '代码>).

Note that HTMLParser.unescape will unescape all HTML entities defined in htmlentitydefs.names2codepoint (plus ').

HTMLParser.unescape 返回与您发布的内容不同的字符.要准确获取这些字符,您可以使用 xml.sax.saxutils:

HTMLParser.unescape returns different characters than what you posted. To get exactly those characters, you might use xml.sax.saxutils:

text='“ ” ·'
import xml.sax.saxutils as saxutils
print(saxutils.unescape(text,{'“':'"', '”':'"', '·':'.', }))
# " " .

请注意,saxutils.unescape 还替换了 <>&代码>.如果您只想替换 “”&middot,那么我会使用 aix 的回答.

Note that saxutils.unescape also replaces <, > and &. If you wish to replace only “, ”, and &middot, then I'd use aix's answer.

这篇关于我可以在python中的一个语句中进行多个字符串替换吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆