【问题标题】:How to strip multiple unwanted characters from a list of strings in python?如何从python中的字符串列表中删除多个不需要的字符?
【发布时间】:2018-08-19 08:03:05
【问题描述】:

我有以下输入字符串:

text='''Although never is often better than *right* now.

If the implementation is hard to explain, it's a bad idea.

If the implementation is easy to explain, it may be a good idea.

Namespaces are one honking great idea -- let's do more of those!'''

到目前为止,我已经将text 字符串拆分为list,如下所示:

list=['Although', 'never', 'is', 'often', 'better', 'than', '*right*', 'now.\n\nIf', 'the', 'implementation', 'is', 'hard', 'to', 'explain,', "it's", 'a', 'bad', 'idea.\n\nIf', 'the', 'implementation', 'is', 'easy', 'to', 'explain,', 'it', 'may', 'be', 'a', 'good', 'idea.\n\nNamespaces', 'are', 'one', 'honking', 'great','idea', '--', "let's", 'do', 'more', 'of', 'those!']

现在,我想使用strip 函数从上面的列表中删除不需要的字符,例如\n\n--

你能帮我解决这个问题吗?

【问题讨论】:

  • stripped = list(map(str.strip,old_list))
  • 请提供您尝试过的代码。
  • 到目前为止你的想法是什么?

标签: python string python-3.x


【解决方案1】:

使用re 模块,re.sub 函数将允许您这样做。 我们需要用单个\n 替换多个\n 出现并删除-- 字符串

import re

code='''Although never is often better than right now.

If the implementation is hard to explain, it's a bad idea.

If the implementation is easy to explain, it may be a good idea.

Namespaces are one honking great idea -- let's do more of those!'''


result = re.sub('\n{2,}', '\n', code)
result = re.sub(' -- ', ' ', result)

print(result)

在 split() 之后你的文本。

【讨论】:

  • 感谢您的回复。我可以知道result = re.sub('\n**{2,}**', '\n', code) 中的 {2,} 是什么吗?
【解决方案2】:

这将使用空格或换行符分割字符串

import re

output = [i for i in re.split(r'\s|\n{1:2}|--', code) if i]

【讨论】:

    【解决方案3】:

    您可以使用列表推导来摆脱--

    >>> code='''Although never is often better than right now.
    If the implementation is hard to explain, it's a bad idea.
    If the implementation is easy to explain, it may be a good idea.
    Namespaces are one honking great idea -- let's do more of those!'''
    >>> 
    >>> [word for word in code.split() if word != '--']
    ['Although', 'never', 'is', 'often', 'better', 'than', 'right', 'now.', 'If', 'the', 'implementation', 'is', 'hard', 'to', 'explain,', "it's", 'a', 'bad', 'idea.', 'If', 'the', 'implementation', 'is', 'easy', 'to', 'explain,', 'it', 'may', 'be', 'a', 'good', 'idea.', 'Namespaces', 'are', 'one', 'honking', 'great', 'idea', "let's", 'do', 'more', 'of', 'those!']
    

    【讨论】:

    • 感谢苏尼莎的回答。但我实际上希望一次尝试删除多个字符.. 就像“--,\n,!,.”提到的应该从我的结果中消失。你能帮我解决这个问题吗?
    • {2,} 表示“2 个或更多”。因此,如果有像 \n\n, \n\n\n, ..., \n\n...\n 这样的序列,它们将被单个 \n 替换
    猜你喜欢
    • 1970-01-01
    • 2011-08-13
    • 2011-02-16
    • 1970-01-01
    • 1970-01-01
    • 2011-12-24
    • 2016-02-01
    相关资源
    最近更新 更多