在for循环中运行replace()方法?

时间:2011-10-18 23:34:57

标签: python string formatting replace

它已经很晚了,我一直在努力研究一个简单的脚本,将点云数据重命名为工作格式。我不知道我做错了什么,因为底部的代码工作得很好。为什么for循环中的代码不起作用?它将它添加到列表中,但它没有被replace函数格式化。对不起,我知道这不是一个调试器,但我真的很困惑,其他人可能需要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()

3 个答案:

答案 0 :(得分:4)

您没有将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()

答案 1 :(得分:3)

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

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

答案 2 :(得分:0)

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

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

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