【问题标题】:Running replace() method in a for loop?在 for 循环中运行 replace() 方法?
【发布时间】:2011-12-10 12:41:33
【问题描述】:

为时已晚,我一直在尝试编写一个简单的脚本来将点云数据重命名为工作格式。我不知道我做错了什么,因为底部的代码工作正常。为什么for循环中的代码不起作用?它将它添加到列表中,但它只是没有被替换函数格式化。抱歉,我知道这不是调试器,但我真的被困在了这个问题上,其他人可能需要 2 秒才能看到问题。

# Opening and Loading the text file then sticking its lines into a list []
filename = "/Users/sacredgeometry/Desktop/data.txt"
text = open(filename, 'r')
lines = text.readlines()
linesNew = []
temp = None


# This bloody for loop is the problem
for i in lines:
    temp = str(i)
    temp.replace(' ', ', ',2)
    linesNew.append(temp)


# DEBUGGING THE CODE    
print(linesNew[0])
print(linesNew[1])

# Another test to check that the replace works ... It does!
test2 = linesNew[0].replace(' ', ', ',2)
test2 = test2.replace('\t', ', ')
print('Proof of Concept: ' + '\n' + test2)


text.close()

【问题讨论】:

    标签: python string formatting replace


    【解决方案1】:

    您没有将replace() 的返回值分配给任何东西。此外,readlinesstr(i) 是不必要的。

    试试这个:

    filename = "/Users/sacredgeometry/Desktop/data.txt"
    text = open(filename, 'r')
    linesNew = []
    
    for line in text:
        # i is already a string, no need to str it
        # temp = str(i)
    
        # also, just append the result of the replace to linesNew:
        linesNew.append(line.replace(' ', ', ', 2))
    
    # DEBUGGING THE CODE    
    print(linesNew[0])
    print(linesNew[1])
    
    # Another test to check that the replace works ... It does!
    test2 = linesNew[0].replace(' ', ', ',2)
    test2 = test2.replace('\t', ', ')
    print('Proof of Concept: ' + '\n' + test2)  
    
    text.close()
    

    【讨论】:

      【解决方案2】:

      字符串是不可变的。 replace 返回一个新字符串,这是您必须插入到 linesNew 列表中的内容。

      # This bloody for loop is the problem
      for i in lines:
          temp = str(i)
          temp2 = temp.replace(' ', ', ',2)
          linesNew.append(temp2)
      

      【讨论】:

        【解决方案3】:

        我遇到了类似的问题,并想出了下面的代码来帮助解决它。我的具体问题是我需要用相应的标签交换字符串的某些部分。我还想要一些可以在我的应用程序的不同位置重复使用的东西。

        使用下面的代码,我可以执行以下操作:

        >>> string = "Let's take a trip to Paris next January"
        >>> lod = [{'city':'Paris'}, {'month':'January'}]
        >>> processed = TextLabeler(string, lod)
        >>> processed.text
        >>> Let's take a trip to [[ city ]] next [[ month ]]
        

        所有代码如下:

        class TextLabeler():
            def __init__(self, text, lod):
                self.text = text
                self.iterate(lod)
        
            def replace_kv(self, _dict):
                """Replace any occurrence of a value with the key"""
        
                for key, value in _dict.iteritems():
                    label = """[[ {0} ]]""".format(key)
                    self.text = self.text.replace(value, label)
                    return self.text
        
            def iterate(self, lod):
                """Iterate over each dict object in a given list of dicts, `lod` """
        
                for _dict in lod:
                    self.text = self.replace_kv(_dict)
                return self.text
        

        【讨论】:

          猜你喜欢
          • 2014-04-13
          • 2017-08-22
          • 1970-01-01
          • 2013-01-12
          • 2017-06-22
          • 1970-01-01
          • 2016-07-18
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多