代码之家  ›  专栏  ›  技术社区  ›  Prashant

如何同时或同时使用多个replace,python

  •  1
  • Prashant  · 技术社区  · 6 年前

    "\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\"
    

    所以为了弄清楚这个标签,我用了

      val.text.replace('\t', '').replace('\n', '').encode('ascii','ignore').
    decode("utf-8").replace('Rated','').replace('  ','')
    

    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('\t', '').replace('\n', '').replace('  ','')
    
    2 回复  |  直到 6 年前
        1
  •  1
  •   dawg    6 年前

    你可以用 .translate \n\t

    >>> 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(' ','')

    >>> 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"
    
        2
  •  0
  •   U13-Forward    6 年前

    replace 但我仍然认为这是最好的方法:

    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+' ']))
    

    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