首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何一起或一次使用多个替换,Python

如何一起或一次使用多个替换,Python
EN

Stack Overflow用户
提问于 2018-06-12 07:52:30
回答 2查看 46关注 0票数 1

我有一些文本不清楚,有这么多的标签和ascii如下,

val =

代码语言:javascript
复制
"\nRated\xa0\n           I have been to this place for dinner tonight.
        \nWell I didn't found anything extraordinary there but indeed a meal worth 
        the price. The number of barbeque item and other both were good.\n\nFood: 3.5/5\"

为了说明我使用的这个标记

代码语言:javascript
复制
  val.text.replace('\t', '').replace('\n', '').encode('ascii','ignore').
decode("utf-8").replace('Rated','').replace('  ','')

使用多次替换,我得到了我的o/p -

代码语言:javascript
复制
I have been to this place for dinner tonight. Well I didn't found anything extraordinary there but indeed a meal worth the price. The number of barbeque item and other both were good. Food: 3.5/5

我想知道有没有什么方法,这样我就可以一次只使用替换来进行类似的替换。就像这个案例-

代码语言:javascript
复制
replace('\t', '').replace('\n', '').replace('  ','')
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-06-12 08:06:07

您可以使用.translate删除\n\t,然后使用您的替换空间运行:

代码语言:javascript
复制
>>> val.translate(None,'\n\t').replace('  ','')
"Rated I have been to this place for dinner tonight.Well I didn't found anything extraordinary there but indeed a meal worth the price. The number of barbeque item and other both were good.Food: 3.5/5"

replace(' ','')在运行偶数个空格时会出现问题(它们将被删除)。您可以考虑使用正则表达式:

代码语言:javascript
复制
>>> re.sub(r'(\b  *\b)',' ',val.translate(None,'\n\t'))
"Rated I have been to this place for dinner tonight.Well I didn't found anything extraordinary there but indeed a meal worth the price. The number of barbeque item and other both were good.Food: 3.5/5"
票数 1
EN

Stack Overflow用户

发布于 2018-06-12 08:03:48

即使我没有使用replace,但我仍然认为这是最好的方式:

代码语言:javascript
复制
import string
val = """\nRated\xa0\n           I have been to this place for dinner tonight.
        \nWell I didn't found anything extraordinary there but indeed a meal worth 
        the price. The number of barbeque item and other both were good.\n\nFood: 3.5/5\"""
        """
print(''.join([i for i in ' '.join(val.split()) if i in string.ascii_letters+' ']))

输出:

代码语言:javascript
复制
Rated I have been to this place for dinner tonight Well I didnt found anything extraordinary there but indeed a meal worth the price The number of barbeque item and other both were good Food 
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50807518

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档