【问题标题】:Stripping out unwanted characters from a list of strings从字符串列表中去除不需要的字符
【发布时间】:2016-03-08 06:31:48
【问题描述】:

我有一个名为file_contents 的字符串列表。 列表中的每个项目都以这种格式的数字开头:#1。 #2。 ETC.. 我想从列表中的每个项目中删除它们。

for item in range(len(file_contents)):
    file_contents[item].lstrip('#' + [item] + ". ")

所以,我想把"#1. Apples" 变成"Apples"

有什么建议吗?

当我运行它时,我收到以下错误:

TypeError: Can't convert 'list' object to str implicitly

这是我定义的整个方法:

def read_from_file(self, filename):
        """Checks if file exists, if it does, reads it in and creates new List object."""
        file_contents = []
        fileExists = os.path.isfile(filename)
        if not fileExists:
            print(filename, "does not exist.")
        else:
            with open(filename) as file:
                file_contents = [line.strip() for line in file]

        for item in range(len(file_contents)):
            file_contents[item] = file_contents[item].lstrip('#' + str(item) + ". ")

        list_name = file_contents[0]
        list_contents = []
        for item in file_contents:
            if item in list_name:
                continue
            else:
                list_contents.append(item)

        new_list = List(list_name)
        new_list.contents = list_contents

        return new_list

【问题讨论】:

  • 如果您显示更多代码,您会得到更好的答案。例如,您的变量名称为 file_contents 的事实表明您可以打开文件并直接对其进行迭代,这里绝对可以避免使用 range(len(file_contents)) 反模式。
  • 我从另一个用户之前删除的评论中发现我的问题与我的 lstrip() 参数的 [item] 部分有关。

标签: python list strip


【解决方案1】:

Regular expressions 非常适合这里:

import re
pattern = re.compile(r'#\d+\.\s*')
new_contents = [pattern.sub('', item) for item in file_contents]

我建议阅读文档链接以了解正则表达式的工作原理,但请简要说明该模式:

  • # - 寻找 # 字符
  • \d+ - 后跟一位或多位数字
  • \. - 然后是一个点字符
  • \s* - 然后是任意数量的空格

re.sub 查找该模式,然后将其替换为 '',一个空字符串 - 从而将其切断。

您还极大地误解了lstrip 和 Python 语法的一般工作原理:

  1. 它不会修改您调用它的字符串,它会返回一个新字符串。
  2. [item] 就是 [0][1] 等,这就是为什么你不能将它连接到字符串。我不太确定你想在那里实现什么。

【讨论】:

    【解决方案2】:

    我认为你的意思是

    stripped_contents = []
    with open('test.data') as f:
        for i, line in enumerate(f):
            strip = '#' + str(i + 1) + ". "
            stripped_line = line.lstrip(strip)
            stripped_contents.append(stripped_line)
    
    print stripped_contents
    

    即您需要将项目转换为字符串而不是列表。另外,由于它从 0 开始,您需要 item + 1。

    另一种解决方案可能是

    stripped_contents = []
    with open('test.data') as f:
        for i, line in enumerate(f):
            start_pos = len('#' + str(i + 1) + ". ")
            stripped_line = line[start_pos:]
            stripped_contents.append(stripped_line)
    
    print stripped_contents
    

    正则表达式也可以。但是对于这样一个简单的问题感觉过于复杂。

    【讨论】:

      【解决方案3】:

      如果您不想从左侧剥离,则将所有字符传递给 lstrip:

      def read_from_file(self, filename):
              """Checks if file exists, if it does, reads it in and creates new List object."""
              file_contents = []
              fileExists = os.path.isfile(filename)
              if not fileExists:
                  return (filename, "does not exist.")
              with open(filename) as file:
                  file_contents = [line.lstrip("0123456789.").strip() for line in file]
      

      您正在删除换行符,因此您可以简单地调用 strip 之后将删除换行符和前导空格:

      In [14]: "#123. 1foo".lstrip("0123456789#.").strip()
      Out[14]: '1foo'
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-06-06
        • 2011-12-24
        • 2018-08-08
        • 1970-01-01
        相关资源
        最近更新 更多