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

5 投票
3 回答
48758 浏览
提问于 2025-04-17 04:35

现在很晚了,我一直在尝试写一个简单的脚本,把点云数据重命名成一个可以用的格式。我不知道自己哪里出错了,因为下面的代码运行得很好。为什么for循环里的代码不行呢?它确实把数据加到了列表里,但就是没有通过替换函数进行格式化。抱歉,我知道这里不是调试器,但我真的卡住了,可能别人看一下就能发现问题。

# 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

我遇到过类似的问题,所以写了下面的代码来解决它。我的具体问题是需要把字符串中的某些部分替换成对应的标签。我还希望这个代码可以在我应用的不同地方重复使用。

通过下面的代码,我可以做到以下几点:

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

字符串是不可改变的。这意味着一旦你创建了一个字符串,就不能直接修改它。replace这个方法会返回一个新的字符串,所以你需要把这个新字符串放到linesNew这个列表里。

# This bloody for loop is the problem
for i in lines:
    temp = str(i)
    temp2 = temp.replace(' ', ', ',2)
    linesNew.append(temp2)
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()

撰写回答