【问题标题】:Remove spaces in " " in List of list of list删除列表列表中“”中的空格
【发布时间】:2020-07-05 15:48:05
【问题描述】:
results = [[['2020 is the year', '29 year old "Samuel G"', '25 year old "John P Krul"', '40 year old "Trey Nunez S"', '22 year old "Fiona S Paul"', '50 year old "Sean J Beal"']]]

我尝试了以下,但这似乎摆脱了python3中“”中的中间词。

print([re.sub(r'"(\w+)(\s(\w+))*"', '"\\1\\3"', x.lower()) for x in results[0]])

我想要的输出是

results = [[['2020 is the year', '29 year old "samuelg"', '25 year old "johnpkrul"', '40 year old "treynunezs"', '22 year old "fionaspaul"', '50 year old "seanjbeal"']]]

仅删除“”中的“”和小写字母之间的“”,以便“John P Krul”到“johnpkrul”,同时保持所有内容相同。

代码需要改什么?

【问题讨论】:

    标签: python regex python-3.x string list


    【解决方案1】:

    你可以试试这个。

    def f(x): #Takes re.match object as input
        a=x.group() #extractting the match
        return a.replace(' ','').lower() #them to lower and removing spaces
    
    [re.sub(r'\"([^"]*)\"',f,i) for i in results]
    

    ['2020 is the year',
     '29 year old "samuelg"',
     '25 year old "johnpkrul"',
     '40 year old "treynunezs"',
     '22 year old "fionaspaul"',
     '50 year old "seanjbeal"']
    

    编辑: 对于列表列表的列表

    [[[re.sub(r'\"([^"]*)\"',f,i) for i in lst2] for lst2 in lst1] for lst1 in results]
    

    输出:

    [[['2020 is the year',
       '29 year old "samuelg"',
       '25 year old "johnpkrul"',
       '40 year old "treynunezs"',
       '22 year old "fionaspaul"',
       '50 year old "seanjbeal"']]]
    

    【讨论】:

    • 这不适用于列表列表。 TypeError:预期的字符串或类似字节的对象
    • 只要你想使用相同的逻辑...我会编辑等待。 @ytoyoyo
    猜你喜欢
    • 2013-04-06
    • 2017-03-05
    • 2014-04-10
    • 1970-01-01
    • 1970-01-01
    • 2014-01-06
    • 2013-10-28
    • 1970-01-01
    • 2022-06-16
    相关资源
    最近更新 更多